gpt4 book ai didi

swift - 无法在强制转换中将类型 'String?' 的值转换为类型 'NSString'

转载 作者:行者123 更新时间:2023-11-28 06:30:54 26 4
gpt4 key购买 nike

我正在尝试为各种数学公式制作这个计算器,但我被困在了这一点上。我在关注这个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

最佳答案

尽可能使用 let 而不是 var。你不需要使用 NSString。您可以将 String 转换为 Float?。您需要同时打开作为字符串的文本属性吗? (如果您对变量选项的类型有疑问,请单击它会向您显示)和 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)"
}

关于swift - 无法在强制转换中将类型 'String?' 的值转换为类型 'NSString',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40384123/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com