gpt4 book ai didi

ios - fatal error : unexpectedly found nil while unwrapping an Optional value (cannot force unwrap value of non-optional type 'String' )

转载 作者:搜寻专家 更新时间:2023-11-01 06:07:03 28 4
gpt4 key购买 nike

我试图将预先附加的字符串作为 URL 请求传递,但我不断收到错误消息: fatal error :在展开可选值时意外发现 nil

此错误指向行:let searchTerm = "http://google.com/#q="+textField.text!

ViewController.swift

func textFieldDidUpdate(textField: UITextField) {

if (textField.text!.rangeOfCharacterFromSet(NSCharacterSet.whitespaceCharacterSet()) != nil) {
self.webView.hidden = false
let searchTerm = "http://google.com/#q="+textField.text!
let request = NSURLRequest(URL: NSURL(string: searchTerm)!)
self.webView.loadRequest(request)
}
}

最佳答案

您应该将方法参数名称更改为 func textFieldDidUpdate(sender: UITextField),使用 guard 解包您的可选文本字段文本属性,并使用查询允许字符集向您的字符串添加百分比转义。

func textFieldDidUpdate(sender: UITextField) {
guard
let text = sender.text,
query = text.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()),
url = NSURL(string: "https://google.com/#q=\(query)")
else { return }
webView.hidden = false
webView.loadRequest(NSURLRequest(URL: url))
}

关于ios - fatal error : unexpectedly found nil while unwrapping an Optional value (cannot force unwrap value of non-optional type 'String' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34834212/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com