28

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!)
 }
Matteo Piombo
  • 6,688
  • 2
  • 25
  • 25
Michel
  • 10,303
  • 17
  • 82
  • 179

4 Answers4

44

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

let number1: Int32 = 10
let number2 = Int(number1)
Eendje
  • 8,815
  • 1
  • 29
  • 31
  • That's very strange. It just works in my playground. What error are you getting? – Eendje Jun 05 '15 at 07:37
  • If the conversion is as you write, then the problem must be different. I edited the question, in order to make things clearer. I want the function to work, I thought the problem was about conversion, but maybe it isn't. I am only making my first steps in Swift. – Michel Jun 05 '15 at 07:39
  • Before looking at your edit, core data returns numbers as `NSNumber` if I'm correct. Usually the typical conversion `Int()` should be enough. – Eendje Jun 05 '15 at 07:42
  • March23 2016; Swift 2.x works! best answer by a mile or more – user3069232 Mar 23 '16 at 08:38
  • `Cannot invoke initializer for type 'Int' with an argument list of type '(() -> Int32)` this is the error that im getting in swift 4 – Sarath Aug 01 '18 at 11:25
  • 1
    @Sarath No problems here, using Swift 4.1. `print(type(of: number2))` prints `Int` just fine. – Eendje Aug 01 '18 at 14:13
  • @Eendje Thanks for your answer and I converted it into string and back to Int. like this `Int("\(Int32value)")` its worked for me. – Sarath Aug 03 '18 at 06:58
10

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
}
Arbitur
  • 38,684
  • 22
  • 91
  • 128
8

Swift 4.0 producing "Cannot invoke initializer for type 'Int' with an argument list of type '(() -> Int32)"

let number1: Int32 = 10
let number2 = Int(number1)

Simply do this

Int("\(Int32value)")

I'm unable to understand why swift is making things difficult.

Aaban Tariq Murtaza
  • 1,155
  • 14
  • 16
2

Sometimes "?" make things twisted , adding "!" to Int32 and then convert it to int works

let number1 = someInt32!
let number2 = Int(number1)
LeoNard
  • 230
  • 1
  • 9