可选类型的值'String?'未解开包装;你的意思是使用'!'还是"?"?|Xcode 建议不起作用



我有以下 Swift 函数

@IBAction func swapText(sender: AnyObject) {
    if let text = textView.text, let findText = findTextField.text,
      let replaceText = replaceTextField.text {
        textView.text =
          textView.text.stringByReplacingOccurrencesOfString(findTextField.text,
            withString: replaceTextField.text, options: [], range: nil)
        findTextField.text = nil
        replaceTextField.text = nil
        view.endEditing(true)
        moveViewDown()
    }
}

findTextField.textreplaceTextField.text都给出了警告:

"Value of optional type 'String?' not unwrapped; did you mean to use
'!' or '?'?"

使用 Xcode 建议的修复实际上并不能解决问题。

我对 Swift 相当陌生,所以任何建议都值得赞赏。

您已经在if let中解开了这些字段(如findTextreplaceText),所以你可以这样做

textView.text =
  text.stringByReplacingOccurrencesOfString(findText,
    withString: replaceText, options: [], range: nil)

就像上面的答案一样,但实际上如果你不以 if-let 开头,你必须通过插入"!"和像这样的变量结尾来解开包装值

if let text = textView.text, let findText = findTextField.text,
      let replaceText = replaceTextField.text {
        textView.text =
          textView!.text.stringByReplacingOccurrencesOfString(findTextField!.text,
            withString: replaceTextField!.text, options: [], range: nil)
        findTextField.text = nil
        replaceTextField.text = nil
        view.endEditing(true)
        moveViewDown()
    }

您也可以跳过多个 let in if-let to。

if let text = textView.text, findText = findTextField.text, replaceText = replaceTextField.text

最新更新