该应用程序基本上通过输入初始和最终速度和时间来计算加速度,然后使用一个公式来计算加速度。但是,由于文本框中的值是字符串,我无法将它们转换为整数。
@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
你可以使用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 5.0及以上
工作
如果你拆分字符串,它会创建两个子字符串,而不是两个字符串。下面的方法将检查任何并将其转换为0 NSNumber很容易将NSNumber转换为Int,浮动任何你需要的数据类型。
实际的代码
//Convert Any To Number Object Removing Optional Key Word.
public func getNumber(number: Any) -> NSNumber{
guard let statusNumber:NSNumber = number as? NSNumber else {
guard let statString:String = number as? String else {
guard let statSubStr : Substring = number as? Substring else {
return 0
}
if let myInteger = Int(statSubStr) {
return NSNumber(value:myInteger)
}
else{
return 0
}
}
if let myInteger = Int(statString) {
return NSNumber(value:myInteger)
}
else if let myFloat = Float(statString) {
return NSNumber(value:myFloat)
}else {
return 0
}
}
return statusNumber }
使用
if let hourVal = getNumber(number: hourStr) as? Int {
}
传递字符串进行检查并转换为Double
Double(getNumber(number: dict["OUT"] ?? 0)
基本想法,注意这只适用于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
...