加法运算符(+)仅在swift中执行连接而不是添加

时间:2015-07-22 11:09:33

标签: ios swift xcode6 operators

对于基本问题道歉,我是斯威夫特的新人,而且我已经被困在这一段时间但却找不到帮助。

我尝试在我的math应用中执行简单的addition操作,例如multiplicationdivisioniOS等操作但是避难所&#39能够。

当我尝试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.
    }


}

3 个答案:

答案 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)