Regarding how to convert a string to a integer:
var myString = "12" //Assign the value of your textfield
if let myInt = myString.toInt(){
//myInt is a integer with the value of "12"
} else {
//Do something, the text in the textfield is not a integer
}
The if let
makes sure that your value can be casted to a integer.
.toInt()
returns an optional Integer. If your string can be casted to a integer it will be, else it will return nil
. The if let
statement will only be casted if your string can be casted to a integer.
Since the new variable (constant to be exact) is a integer, you can make a new variable and add 5 to the value of your integer
var myString = "12" //Assign the value of your textfield
if let myInt = myString.toInt(){
//myInt is a integer with the value of “12”
let newInt = myInt + 5
myTextfield.text = "\(newInt)"
//The text of the textfield will be: "17" (12 + 5)
} else {
//Do something, the text in the textfield is not a integer
}