Swift: 如果让难题

Swift: If Let Conundrum

现在我知道关于 Initializer for conditional binding must have optional type 错误的其他问题已经得到解答,但我已经尝试了这些解决方案并且 none 似乎工作或关于 NSURL。我的是专门谈论它不能是 NSURL。我不知道该怎么做才能解决它。

let attemptedUrl = NSURL(string: "http://www.weather-forecast.com/locations/" +
textField.text!.stringByReplacingOccurrencesOfString(" ", withString: "-") + 
"/forecasts/latest")!

if let url = attemptedUrl {

出错的具体代码行是 如果让 url = attemptedUrl {

你正在强制解包你调用 NSURL(string:) 的结果,这就是!在该语句的末尾执行。因此,您的 attemptedUrl 变量不是可选类型,因此使用 if let 语句再次展开它(除了使用 ! 语句强制展开)是多余的并且不会编译。

我建议阅读 Optionals section of The Swift Programming Language 以获取更多信息。