表达式类型 '@lvalue String?'当 += 到 UILabel.text 时,没有更多上下文是不明确的 [英] Expression type '@lvalue String?' is ambiguous without more context when += to UILabel.text
问题描述
当有人点击标记为 7 的按钮时,我试图将字符串7"添加到标签中.
I am trying to add the string "7" to a label when someone tabs the button labeled 7.
但是当使用 += "7" 时,它给了我错误表达式类型 '@lvalue String?'在没有更多上下文的情况下是模棱两可的",当使用 operator = "7" 时它工作正常.为什么 += "7" 不起作用?
But when using += "7", it gives me the error "Expression type '@lvalue String?' is ambiguous without more context", when using the operator = "7" it works fine. Why doesn't += "7" work?
class NumberPadController: UIViewController {
@IBOutlet weak var valueLabel: UILabel!
/// set value in main vc and return to that.
@IBAction func doneEntering(_ sender: Any) {
guard let valueString = valueLabel.text, let valueDouble = Double(valueString), let presentingVC = self.presentingViewController as? ViewController else {
// FIXME: Show error
dismiss(animated: true, completion: nil)
return
}
presentingVC.valuePassedFromNumPad = valueDouble
dismiss(animated: true, completion: nil)
}
@IBAction func seven(_ sender: Any) {
valueLabel.text += "7" // Expression type '@lvalue String?' is ambiguous without more context
valueLabel.text = "a" // works fine
}
}
推荐答案
text
属性是可选.一种安全的方法是使用 append
和 optional chaining:
The text
property is optional. One way to do this safely would be to use append
along with optional chaining:
valueLabel.text?.append("7")
或使用 +=
和 可选链:
valueLabel.text? += "7"
如果标签是 nil
,这些将安全地什么都不做.如果您希望标签为 "7"
如果它是 nil
,则使用 @RickyMo 的解决方案.
If the label is nil
, these would safely do nothing. If you'd like the label to be "7"
if it was nil
, then use @RickyMo's solution.
这篇关于表达式类型 '@lvalue String?'当 += 到 UILabel.text 时,没有更多上下文是不明确的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!