I am trying to build an app that makes calculations. My interface shows the numbers in a label. When I try to convert the label.text to an int, to add it to something else I get a nullable (int?) and they cannot be used with "+". How do I convert an int? to int in swift?
            Asked
            
        
        
            Active
            
        
            Viewed 2,752 times
        
    2
            
            
        - 
                    Basically you have to unpack your optional. Take a look here: http://stackoverflow.com/questions/24030053/use-of-an-optional-value-in-swift – 3vangelos Dec 08 '15 at 12:56
- 
                    That is called an "Optional" in Swift, not a nullable. Optionals are a key concept of Swift and well documented in the Swift book. – Martin R Dec 08 '15 at 13:05
- 
                    See also this thread: http://stackoverflow.com/questions/24115141/swift-converting-string-to-int. – Martin R Dec 08 '15 at 13:08
1 Answers
1
            Code example for the problem:
     let a:Int? = Int(firstText.text) // firstText is UITextField
     let b:Int? = Int(secondText.text) // secondText is UITextField
        if let first = a as? Int, second = b as? Int {
            var ans = first + second
            answerLabel.text = "Answer is \(ans)"       // answerLabel ie UILabel
        } else {
            answerLabel.text = "Input values are not numberic"
        }
 
    
    
        Oleg Gordiichuk
        
- 15,240
- 7
- 60
- 100
- 
                    `toInt()` is Swift 1.x and won't compile with the current Xcode anymore. – Martin R Dec 08 '15 at 13:09
- 
                    
 
    