问题
I am trying to add the string "7" to a label when someone tabs the button labeled 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
}
}
回答1:
The text
property is optional. One way to do this safely would be to use append
along with optional chaining:
valueLabel.text?.append("7")
or use +=
with optional chaining:
valueLabel.text? += "7"
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.
回答2:
text
property is optional. To do it safely :
valueLabel.text = (valueLabel.text ?? "") + "7"
来源:https://stackoverflow.com/questions/55056650/expression-type-lvalue-string-is-ambiguous-without-more-context-when-to-u