Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert Int32 to Int in Swift?

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!)  } 
like image 560
Michel Avatar asked Jun 05 '15 07:06

Michel


People also ask

How to change string into Int Swift?

Using Int initializer Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer.

What is Int32 in Swift?

Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit forms. These integers follow a naming convention similar to C, in that an 8-bit unsigned integer is of type UInt8 , and a 32-bit signed integer is of type Int32 . Like all types in Swift, these integer types have capitalized names.


2 Answers

Am I missing something or isn't this ridiculously easy?

let number1: Int32 = 10 let number2 = Int(number1) 
like image 86
Eendje Avatar answered Sep 27 '22 20:09

Eendje


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:

return Int(myUnit.valueForKey(“theNUMBER”)!.intValue) 

But you could also do like this if you want it to be fail safe:

return myUnit.valueForKey(“theNUMBER”)?.integerValue ?? 0 

And to shorten you function you can do this:

func myNumber() -> Int {     let myUnit = self.getObject("EntityName") as! NSManagedObject      return myUnit.valueForKey("theNUMBER")?.integerValue ?? 0 } 
like image 23
Arbitur Avatar answered Sep 27 '22 20:09

Arbitur