【问题标题】:Cannot convert value of type 'String?' to type 'NSString' in coercion无法转换“字符串”类型的值?强制输入“NSString”
【发布时间】:2016-11-02 15:46:13
【问题描述】:

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

这是我的代码:

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.
}

}

我得到错误的部分是:

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

【问题讨论】:

  • 为什么要使用NSString?斯威夫特有String。并且最好使用NSNumberFormatter 尝试将用户输入的数字转换为实际数字。
  • 并且您需要处理用户输入的无效值。
  • 教程太多了……

标签: swift xcode nsstring


【解决方案1】:

在可能的情况下,首选 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)"
}

【讨论】:

  • 您的代码中没有强制转换。 Float(aText) 不是演员表,而是转换。显着差异。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-08
  • 2017-08-25
  • 2016-08-11
  • 2016-12-18
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多