How can I convert Int32 to Int in Swift?

前端 未结 4 1602
抹茶落季
抹茶落季 2021-01-03 20:16

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

相关标签:
4条回答
  • 2021-01-03 20:29

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

    let number1 = someInt32!
    let number2 = Int(number1)
    
    0 讨论(0)
  • 2021-01-03 20:33

    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.

    0 讨论(0)
  • 2021-01-03 20:47

    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
    }
    
    0 讨论(0)
  • 2021-01-03 20:48

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

    let number1: Int32 = 10
    let number2 = Int(number1)
    
    0 讨论(0)
提交回复
热议问题