It should be easy but I can only find the reverse conversion. How can I convert Int32 to Int in Swift? Unless the problem is different?
I have a value stored in Core Data and I want to return it as an Int.
Here is the code I am using, which does not work:
func myNumber () -> Int {
var myUnit:NSManagedObject
myUnit=self.getObject(“EntityName”) // This is working.
return Int(myUnit.valueForKey(“theNUMBER”)?.intValue!)
}
The error is your ? after valueForKey.
Int initializer doesnt accept optionals.
By doing
myUnit.valueForKey(“theNUMBER”)?.intValue!
gives you an optional value and the ! at the end doesnt help it.Just replace with this:
But you could also do like this if you want it to be fail safe:
And to shorten you function you can do this: