为什么 UITextFIeld return 中的可选值 Swift?

Why does UITextFIeld return optional value in Swift?

我使用 UITextField 输入数字,但当我输入第一个数字时,它最终打印 nil。然后,当我输入其他数字时,它会打印出我输入的数字,但类型为 optional return 。为什么会这样?

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    //convert string into number
    let input = (numberLabel.text! as NSString).integerValue

    //find answer to label when added by 1111
    let answer = input + 1111
    print(answer)

    let numberText = Int(numberField.text!)
    print("This is number text: \(numberText)

    if answer == numberText {
        print("correct")
        //if user gets answer correct
    } else {
        //if user gets answer incorrect
    }
}

UITextFied 文本 属性 永远不会 return nil。它的默认值是一个空字符串。 returning nil 是 Int 字符串初始值设定项。关于文本 属性 可选性,IMO 有意允许您分配一个可选字符串,而无需先将其解包。

let numberText = Int(textField.text!) ?? .zero

原因可能是因为您使用的 shouldChangeCharactersIn 直到第二个字符才表示字符的变化。理想情况下,您希望用户在完成答案并提交后收到正确答案的通知,在这种情况下,您希望使用类似 textFieldDidEndEditing:

的内容
class MyVC: UIViewController, UITextFieldDelegate {
    let textField = UITextField()
    var numberLabel: UILabel {
        let label = UILabel()
        label.text = "100"
        return label
    }
    let button = UIButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(textField)
        textField.borderStyle = .roundedRect
        textField.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            textField.widthAnchor.constraint(equalToConstant: 200),
            textField.heightAnchor.constraint(equalToConstant: 100)
        ])
        textField.delegate = self
        
        button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
        button.tag = 1
        button.backgroundColor = .black
        button.setTitle("Answer", for: .normal)
        self.view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            button.leadingAnchor.constraint(equalTo: textField.trailingAnchor),
            button.widthAnchor.constraint(equalToConstant: 200),
            button.heightAnchor.constraint(equalToConstant: 100)
        ])
        
    }
    
    @objc func buttonPressed(_ sender: UIButton!) {
        if case let tag = sender.tag, tag == 1 {
            textField.resignFirstResponder()
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        //convert string into number
        let input = (numberLabel.text! as NSString).integerValue
        
        //find answer to label when added by 1111
        let answer = input + 1111
                print(answer)
        
        if let numberText = Int(textField.text ?? "0") {
            print("This is number text: \(numberText)")
            
            if answer == numberText {
                //if user gets answer correct
                print("correct")
            } else {
                //if user gets answer incorrect
                print("wrong")
            }
        }
    }

}