在Swift中将String转换为Int

时间:2015-05-07 13:02:25

标签: swift

你好我是Swift的新手,我正在Xcode中构建一个计算器。在我的主要故事板中,我有UIButtonUILabelUITextField将获得一个数字,按下按钮,标签的文字应显示输入的数字+ 5.在我的应用中我需要将String变量转换为Int

我尝试了下面的代码片段,但没有得到任何有意义的结果。

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

4 个答案:

答案 0 :(得分:8)

为了使其干净并且 Swifty ,我建议采用这种方法:

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
}

答案 1 :(得分:2)

如果你想用这个新整数计算,你必须在变量名后加一个感叹号来解开它:

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

print(intnumber!+3)

结果将是:

15

答案 2 :(得分:0)

string joined = string.Join(",", duplicateItems);

答案 3 :(得分:0)

关于如何将字符串转换为整数:

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
}

if let确保您的值可以转换为整数 .toInt()返回一个可选的Integer。如果你的字符串可以被转换为整数,那么它将返回nil。只有在您的字符串可以转换为整数时,if let语句才会被转换。

由于新变量(精确常量)是一个整数,您可以创建一个新变量并将5加到整数值

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
}