Swift giving Optional(3) instead of 3 for .toInt

前端 未结 3 1036
迷失自我
迷失自我 2021-01-29 13:51

Trying to pull a number from a Field and keep getting Optional(number) instead of the number

@IBOutlet weak var years: UITextField!

@IBAction func calculateYear         


        
相关标签:
3条回答
  • 2021-01-29 14:05

    That happens because the toInt() method returns an optional, to account for the case when the string is not convertible to an integer.

    Just put that in an optional binding:

    if let a = a {
        println(a)
    }
    
    0 讨论(0)
  • 2021-01-29 14:14

    toInt() returns an optional because the conversation to an integer can fail. Consider the case where the user enters something other than a number. When the user enters "Blah", what do you expect toInt() to return?

    You need to conditionally unwrap the optional

    if let a = years.text.toInt() {
        println(a)
    }
    
    0 讨论(0)
  • 2021-01-29 14:24

    I also found forced unwrapping by changing a to a! worked as well. thanks to all who tried to help.

    0 讨论(0)
提交回复
热议问题