Convert AnyObject to an Int - ios

I'm trying to convert a anyObject to an Int. Here's my code:
println(currentObject[0])
println(_stdlib_getDemangledTypeName(currentObject[0]))
2
Swift.ImplicitlyUnwrappedOptional<Swift.AnyObject>
I'm trying to convert currentObject[0] to an Int. Here's what I tried:
let num: Int = currentObjec[0] as! Int
When I run the app, I get the following error:
Could not cast value of type '__NSCFString' (0x103c93c50) to 'NSNumber' (0x103535b88)
When I try this: currentObject[0].toInt()
I get an error saying
'AnyObject' does not have a member named 'toInt()'
The only way I'm able to make it work, is to do the following:
let numStr = currentObject[0] as! String
let num: Int = numStr.toInt()!
Is there a simpler way to do it? (Without having to first convert it to a String.)

From the error message
Could not cast value of type '__NSCFString' (0x103c93c50) to 'NSNumber' (0x103535b88)
you can conclude that currentObject[0] is actually an NSString.
In that case you can simply convert it with
let numStr = currentObject[0].integerValue
But note that this will crash if the array element is not an NSString.

Related

Casting Int database value into CoreData issue

I am trying to load some values from my firebase database directly into CoreData, the value in question is an integer but the issue is CoreData wants a Int64, Int32, or Int16, and it's not possible to downcast Ints in swift, So I am getting an error on the line of code where I assign the CoreData attribute to the database value. The database returns 0 (value will only be 0 or 1). Casting the database value as an Int64 is giving me an error. The bilateral_unilat attribute is of type Int64. How can I save an Int value into CoreData?
cdExercise.bilat_unilat = (exercise.childSnapshot(forPath: "bilat_unilat").value as! Int64)
this is the error:
Could not cast value of type 'NSTaggedPointerString' (0x7fff87a91958) to 'NSNumber' (0x7fff87b50b80).
in the debugger window I can print out a value of 0, which is the expected value, with this line of code:
po (exercise.childSnapshot(forPath: "bilat_unilat").value as! NSNumber)
Not sure what the issue is here
If you're attempting to get to a NSNumber as the end result, here's a couple of options
let aInt = snapshot.childSnapshot(forPath: "bilat_unilat").value as? Int ?? 0
let aNum = NSNumber(integerLiteral: aInt)
or just do it directly
let aNum = snapshot.childSnapshot(forPath: "bilat_unilat").value as! NSNumber
*note I omitted error handling for brevity and assumes the value of the bilat_unilat node is in fact an Int
The error
Could not cast value of type 'NSTaggedPointerString' (0x7fff87a91958) to 'NSNumber' (0x7fff87b50b80)
is misleading.
value is apparently NSNumber so cast it to NSNumber and then to Int64
let bilatUnilat = exercise.childSnapshot(forPath: "bilat_unilat").value as! NSNumber
cdExercise.bilat_unilat = bilatUnilat as! Int64
If the value is only 0 or 1 I recommend to declare the attribute as Bool
let bilatUnilat = exercise.childSnapshot(forPath: "bilat_unilat").value as! NSNumber
cdExercise.bilat_unilat = bilatUnilat == 1
And please name the Core Data attributes according to the naming convention lowerCamelCased

can't get number from NSArrayM

i get the below error when trying to retrieve a key name from a query. and then cast it as an int of use by viewcontroller.
Could not cast value of type '__NSArrayM' (0x1073ebdb0) to 'NSNumber' (0x1069f3488).
this is the line in the query:
tempVarLDS = object.value(forKey: keyName)
when printed this returns
(
7
)
so it is an array. but i can't seem to access it via
tempvarLDS[0]
or any of the usual suspects. any idea how to get this int?
If it's an NSArray of NSNumbers, you should be able to cast it as an array of integers.
// Cast it
let tempvarLDS:[Int] = object.value(forKey: keyName) as! [Int]
// Loop
for num in tempvarLDS {
print(num)
}
I don't see why that wouldn't work

Core Data and making double from type AnyObject? Swift

I was writing a code for CoreData. My datamodel includes name and moneyAmount. Here's the part of the code I have troubles with
do {
let request = NSFetchRequest(entityName: "MoneyData")
let results = try context.executeFetchRequest(request)
if results.count > 0 {
for item in results as! [NSManagedObject] {
let name = String(item.valueForKey("name"))
let moneyAmount = item.valueForKey("moneyAmount")
moneyManager.addMoney(name, moneyAmount: moneyAmount)
}
}
} catch {
print("There was an error saving data")
}
Now the problem is that my moneyManager.addMoney requires String and Double. However, with this code, the error that I get is:
Optional Chain has no effect, already produces 'Anyobject?'
Cannot convert value of type AnyObject? to expected argument type 'Double'
I don't really understand what it means by Anyobject. I think I should convert anyobject to double to make it work right?
Thanks in advance
valueForKey() returns an object of type AnyObject because there's no way of knowing at compile-time what type of object it's referencing. You can cast to a specific type using as. For example, moneyAmount as? Double will result in an object of type Double?, either containing the numeric value, or being nil if the object wasn't of type Double.

swift forcing objective-c int to be assigned as Int32 then crashing

I have an objective c property that has been declared as
#property int xmBufferSize;
If I do sharedExample.xmBufferSize = 1024 it just works fine
but when I am trying to set an integer value for that property from another variable
var getThat:Int = dict["bufferSize"]!.integerValue
sharedExample.xmBufferSize = getThat
It can't do above
Cannot assign a value of type 'Int' to a value of type 'Int32'
If I force this to
sharedExample.xmBufferSize =dict["bufferSize"] as! Int32
It is crashing with Error
Could not cast value of type '__NSCFNumber' to 'Swift.Int32'
EDIT::::
Dict init, there are other objects in dict besides integers
var bufferSize:Int = 1024
var dict = Dictionary<String, AnyObject>() = ["bufferSize":bufferSize]
The value in dict is an NSNumber, which cannot be cast or directly converted to Int32. You can first obtain the NSNumber and then call intValue on it:
if let bufferSize = dict["bufferSize"] as? NSNumber {
sharedExample.xmlBufferSize = bufferSize.intValue
}
The if let … as? allows you to verify that the value is indeed an NSNumber, since (as you said) there can be other types of objects in dict. The then-branch will only execute if dict["bufferSize"] exists and is an NSNumber.
(Note: You can also try integerValue if intValue gives the wrong type, or convert the resulting integer – CInt(bufferSize.integerValue) – as needed. Swift doesn't do implicit conversions between different integer types, so you need to match exactly.)
You need to convert your NSNumber to Int32.
sharedExample.xmBufferSize = dict["bufferSize"]!.intValue
Use type conversion, not as:
sharedExample.xmBufferSize = Int32(dict["bufferSize"] as! Int)
That should work.

Cast from 'Int?' to unrelated type 'NSNumber' always fails

When I try to do the line below, I dont get a warning (not an error). What is this am I am doing something bad?
I am trying to cast the integer earningsSoFar to a NSNumber because I want to get the .stringValue out of it.
I want to understand what is the warning mean here and how to do this right.
self.tv_salaryNumber.text = (earningsSoFar as! NSNumber).stringValue
You can cast Int to NSNumber in this way
let a:Int? = 10
let b = a! as NSNumber
So,in your code,just try
self.tv_salaryNumber.text = (earningsSoFar! as NSNumber).stringValue
Also,as zeneak said,you can make it easier in his way

Resources