该应用程序基本上通过输入初始和最终速度和时间来计算加速度,然后使用一个公式来计算加速度。但是,由于文本框中的值是字符串,我无法将它们转换为整数。

@IBOutlet var txtBox1 : UITextField
@IBOutlet var txtBox2 : UITextField
@IBOutlet var txtBox3 : UITextField
@IBOutlet var lblAnswer : UILabel


@IBAction func btn1(sender : AnyObject) {

    let answer1 = "The acceleration is"
    var answer2 = txtBox1
    var answer3 = txtBox2
    var answer4 = txtBox3

当前回答

在Swift 4.2和Xcode 10.1中

let string = "789"
if let intValue = Int(string) {
    print(intValue)
}

let integerValue = 789
let stringValue = String(integerValue)

OR

let stringValue = "\(integerValue)"
print(stringValue)

其他回答

//Xcode 8.1和swift 3.0

我们也可以通过可选绑定来处理它

let occur = "10"

if let occ = Int(occur) {
        print("By optional binding :", occ*2) // 20

    }

基本想法,注意这只适用于Swift 1。(查看ParaSara的回答,看看它是如何在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"
    }

Swift 4更新

...
let a:Int? = Int(firstText.text) // firstText is UITextField
let b:Int? = Int(secondText.text) // secondText is UITextField
...

这对我很有用

var a:Int? = Int(userInput.text!)

Swift5 float或int string to int:

extension String {
    func convertStringToInt() -> Int {
        return Int(Double(self) ?? 0.0)
    }
}

let doubleStr = "4.2"
// print 4
print(doubleStr.convertStringToInt())

let intStr = "4"
// print 4
print(intStr.convertStringToInt())

我的解决方案是有一个一般的扩展字符串到int转换。

extension String {

 // default: it is a number suitable for your project if the string is not an integer

    func toInt(default: Int) -> Int {
        if let result = Int(self) {
            return result
        }
        else {
            return default  
        }
    }

}