Mahdi Appleseed
Mahdi Appleseed

Reputation: 79

Converting String to Int in Swift

Hello I'm new to Swift and I'm building a calculator in Xcode. In my main storyboard I have a UIButton, UILabel and a UITextField that will get a number and by pressing the button, label's text should show the entered number + 5. In my app I need to convert a String variable to Int.

I tried the snippet below I didn't get any meaningful result.

var e = texti.text
let f: Int? = e.toInt()
let kashk = f * 2
label.text = "\(pashm)"

Upvotes: 1

Views: 12855

Answers (4)

Michal
Michal

Reputation: 15669

To make it clean and Swifty, I suggest this approach:

Swift 2 / 3

var string = "42" // here you would put your 'texti.text', assuming texti is for example UILabel

if let intVersion = Int(string) { // Swift 1.2: string.toInt()
    let multiplied = 2 * intVersion
    let multipliedString = "\(multiplied)"
    // use the string as you wish, for example 'texti.text = multipliedString'
} else {
    // handle the fact, that toInt() didn't yield an integer value
}

Upvotes: 8

Jannick
Jannick

Reputation: 81

If you want to calculate with that new integer you have to unwrap it by putting an exclamation mark behind the variable name:

let stringnumber = "12"
let intnumber:Int? = Int(stringnumber)

print(intnumber!+3)

The result would be:

15

Upvotes: 2

milo526
milo526

Reputation: 5083

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
}

Upvotes: 0

Esqarrouth
Esqarrouth

Reputation: 39201

var string = "12"
var intVersion = string.toInt()
let intMultipied = intVersion! * 2
label.text= "\(intMultipied)"

Upvotes: 0

Related Questions