Expression type '@lvalue String?' is ambiguous without more context when += to UILabel.text

我是研究僧i 提交于 2021-01-29 11:43:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!