Posts

Showing posts with the label Uitextfield

Converting String To Int With Swift

Answer : Updated answer for Swift 2.0+ : toInt() method gives an error, as it was removed from String in Swift 2.x. Instead, the Int type now has an initializer that accepts a String : let a: Int? = Int(firstTextField.text) let b: Int? = Int(secondTextField.text) Basic Idea, note that this only works in Swift 1.x (check out ParaSara's answer to see how it works in Swift 2.x): // toInt returns optional that's why we used a:Int? let a:Int? = firstText.text.toInt() // firstText is UITextField let b:Int? = secondText.text.toInt() // secondText is UITextField // check a and b before unwrapping using ! if a && b { var ans = a! + b! answerLabel.text = "Answer is \(ans)" // answerLabel ie UILabel } else { answerLabel.text = "Input values are not numeric" } Update for Swift 4 ... let a:Int? = Int(firstText.text) // firstText is UITextField let b:Int? = Int(secondText.text) // secondText is UITextField...