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

@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

当前回答

因为字符串可能包含非数字字符,所以应该使用保护来保护操作。例子:

guard let labelInt:Int = Int(labelString) else {
    return
}

useLabelInt()

其他回答

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())

你可以使用NSNumberFormatter(). numberfromstring (yourNumberString)。这很好,因为它返回一个可选的,然后你可以用if let测试,以确定转换是否成功。 如。

var myString = "\(10)"
if let myNumber = NSNumberFormatter().numberFromString(myString) {
    var myInt = myNumber.integerValue
    // do what you need to do with myInt
} else {
    // what ever error code you need to write
}

斯威夫特5

var myString = "\(10)"
if let myNumber = NumberFormatter().number(from: myString) {
    var myInt = myNumber.intValue
    // do what you need to do with myInt
  } else {
    // what ever error code you need to write
  }

在Swift 4中:

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

斯威夫特4.0

let stringNumber = "123"
let number = Int(stringNumber) //here number is of type "Int?"


//using Forced Unwrapping

if number != nil {         
 //string is converted to Int
}

你也可以使用可选绑定而不是强制绑定。

eg:

  if let number = Int(stringNumber) { 
   // number is of type Int 
  }

最新的swift3这段代码只是简单地将字符串转换为int

let myString = "556"
let myInt = Int(myString)