xcode 无法转换“字符串”类型的值?强制输入“NSString”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40384123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:32:10  来源:igfitidea点击:

Cannot convert value of type 'String?' to type 'NSString' in coercion

swiftxcodensstring

提问by sebiraw

Im trying to make this calculator for various math formulas and I'm stuck at this point. I was following this tutorial

我正在尝试为各种数学公式制作这个计算器,但我被困在了这一点上。我正在关注本教程

Here's my code:

这是我的代码:

import UIKit

class pythagorasViewController: UIViewController {


@IBOutlet weak var aLabel: UILabel!
@IBOutlet weak var bLabel: UILabel!
@IBOutlet weak var aField: UITextField!
@IBOutlet weak var bField: UITextField!
@IBOutlet weak var answerLabel: UILabel!
@IBAction func calculateButton(_ sender: UIButton) {
    var a = (aField.text as NSString).floatValue
    var b = (bField.text as NSString).floatValue
    var answer = sqrt(a*a + b*b)
    answerLabel.text = "\(answer)"
}

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

The part where I'm getting the error is at:

我收到错误的部分是:

var a = (aField.text as NSString).floatValue
var b = (bField.text as NSString).floatValue

采纳答案by Josh Homann

Prefer let to var when possible. You do not need to use NSString. You can cast String to Float?. You need to unwrap both the text property which is a String? (if you have a question about the type of a variable option click and it will show you) and the Float? conversion:

在可能的情况下更喜欢 let 到 var 。您不需要使用 NSString。您可以将 String 转换为 Float?。您需要解开作为字符串的文本属性吗?(如果您对变量选项的类型有疑问,请单击它,它会显示给您)和浮动?转换:

func calculateButton(_ sender: UIButton) {
    guard let aText = aField.text,
          let bText = bField.text,
          let a = Float(aText),
          let b = Float(bText) else {
        return
    }
    let answer = sqrt(a*a + b*b)
    answerLabel.text = "\(answer)"
}