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

@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

当前回答

//Xcode 8.1和swift 3.0

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

let occur = "10"

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

    }

其他回答

用这个:

// get the values from text boxes
    let a:Double = firstText.text.bridgeToObjectiveC().doubleValue
    let b:Double = secondText.text.bridgeToObjectiveC().doubleValue

//  we checking against 0.0, because above function return 0.0 if it gets failed to convert
    if (a != 0.0) && (b != 0.0) {
        var ans = a + b
        answerLabel.text = "Answer is \(ans)"
    } else {
        answerLabel.text = "Input values are not numberic"
    }

OR

使你的UITextField KeyboardType为DecimalTab从你的XIB或故事板,并删除任何if条件做任何计算,即。

var ans = a + b
answerLabel.text = "Answer is \(ans)"

因为键盘类型是DecimalPad,没有机会输入其他0-9或。

希望这对你有帮助!!

转换字符串值为整数在Swift 4

let strValue:String = "100"
let intValue = strValue as! Int
var intValueFromString:Int = strValue as! Int
or
var intValueFromString = Int(strValue)!

在Swift 4中:

extension String {            
    var numberValue:NSNumber? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter.number(from: self)
    }
}
let someFloat = "12".numberValue

我最近也遇到了同样的问题。下面的解决方案对我来说是可行的:

        let strValue = "123"
        let result = (strValue as NSString).integerValue

问题:字符串“4.000”不能转换成整数使用Int(“4.000”)?

答案:Int()检查字符串是否是整数,如果是,然后给你整数,否则为nil。但是Float或Double可以将任何数字字符串转换为各自的Float或Double而不给nil。例如,如果你有“45”整数字符串,但使用Float("45")会给你45.0浮点值,或使用Double("4567")会给你45.0。

解决方案:NSString(string: "45.000").integerValue或Int(Float("45.000")!)!才能得到正确的结果。