1

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)"
Michal
  • 15,429
  • 10
  • 73
  • 104
Mahdi Appleseed
  • 79
  • 1
  • 3
  • 11

4 Answers4

8

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
}
Community
  • 1
  • 1
Michal
  • 15,429
  • 10
  • 73
  • 104
2

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
Stephan Schielke
  • 2,744
  • 7
  • 34
  • 40
Jannick
  • 81
  • 1
  • 5
0
var string = "12"
var intVersion = string.toInt()
let intMultipied = intVersion! * 2
label.text= "\(intMultipied)"
Esqarrouth
  • 38,543
  • 21
  • 161
  • 168
0

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
}
milo526
  • 5,012
  • 5
  • 41
  • 60
  • 1
    I seriously should stop answering when i’m not behind my mac using xCode, thanks @LeonardoSavioDabus – milo526 May 07 '15 at 13:36
  • I’ve we’re gonna play it that way, why not use `myTextfield.text = “\(myInt + 5)”` and make no new constant at all? – milo526 May 07 '15 at 13:38
  • Question was pretty “basic” better wright it out I think since I suspect OP is new to swift – milo526 May 07 '15 at 13:39