对于基本问题道歉,我是斯威夫特的新人,而且我已经被困在这一段时间但却找不到帮助。
我尝试在我的math
应用中执行简单的addition
操作,例如multiplication
,division
和iOS
等操作但是避难所&#39能够。
当我尝试add
两个double
个数字(weightField
和heightField
)时,我会得到一个连结string
而不是sum
。
如何在swift中执行简单的数学运算?
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var weightField: UITextField!
@IBOutlet weak var heightField: UITextField!
@IBAction func goButton(sender: AnyObject) {
resultField.text = weightField.text + heightField.text
}
@IBOutlet weak var resultField: UILabel!
@IBOutlet weak var commentField: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:2)
您不会将字符串的值添加到一起,因此如果您确定文本可以转换为Int
,则可以执行以下操作:
// in Swift 1.x
resultField.text = String(weightField.text.toInt()! + heightField.text.toInt()!)
// and double values
let weight = (weightField.text as NSString).doubleValue
let height = (heightField.text as NSString).doubleValue
resultField.text = String(weight + height)
// but if it cannot parse the String the value is 0.0. (No optional value)
// in Swift 2
resultField.text = String(Int(weightField.text)! + Int(heightField.text)!)
// and you can even use a double initializer
resultField.text = String(Double(weightField.text)! + Double(heightField.text)!)
答案 1 :(得分:1)
使用NSString:
resultField.text = String(stringInterpolationSegment: (weightField.text as NSString).doubleValue + (heightField.text as NSString).doubleValue)
答案 2 :(得分:0)
基本上你是连接字符串而不是数字。您需要将字符串转换为整数,然后添加它们。
var a = weightField.text
var b = heightField.text
var c = (a as! NSString).doubleValue + (b as! NSString).doubleValue
resultField.text = String(format "%.2f",c)