加法运算符 (+) 只执行连接而不是 swift 中的加法

Addition operator (+) only performing concatenation instead of addition in swift

很抱歉回答这个基本问题,我是 swift 的新手,我已经被困在这个问题上一段时间了,但没有找到帮助。

我正在尝试在我的 iOS 应用程序中执行简单的 math 操作,例如 additionmultiplicationdivision 等,但还没有能够。

当我尝试 add 两个 double 数字(weightFieldheightField)时,我得到一个串联的 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.
    }


}

基本上你连接的是字符串而不是数字。您需要将字符串转换为整数,然后将它们相加。

var a = weightField.text

var b =  heightField.text

var c = (a as! NSString).doubleValue +  (b as! NSString).doubleValue

resultField.text = String(format "%.2f",c)

您不会将字符串的值相加,因此如果您确定文本可转换为 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)!)

使用 NSString:

resultField.text = String(stringInterpolationSegment: (weightField.text as NSString).doubleValue + (heightField.text as NSString).doubleValue)