在我制作的程序中,我试图访问网络内容以显示天气。我正在为可选的概念而苦苦挣扎,我想知道为什么这行代码在“?”时起作用。添加,但并非没有。
@IBAction func pressedSearch(sender: AnyObject) {
var urlString = "http://www.weather-forecast.com/locations/" + cityField.text.stringByReplacingOccurrencesOfString(" ", withString: "") + "/forecasts/latest"
var url = NSURL(string: urlString)
println(urlString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding)
var contentArray = urlContent?.componentsSeparatedByString("<span class=\"phrase\">") as Array<String>
println(contentArray[1])
}
task.resume()
}
这是“?”所在的代码行添加以使代码工作:
var contentArray = urlContent?.componentsSeparatedByString("<span class=\"phrase\">") as Array<String>
“?”是什么意思?做修复错误,为什么我们必须添加“?”和 ”!”在整个 swift 中对某些变量而不是其他变量?
请您参考如下方法:
这里有一些代码可以帮助您更好地理解 ? 和 !(包括您告诉机器的内容):
var foo = resultOfAFunctionThatReturnsAQuestionMarkValue()
foo.accessFunction() // "<silence>..."
// this could break if foo is nil
var bar = resultOfAFunctionThatReturnsAQuestionMarkValue()
bar?.accessFunction() // "Hey, bro. This might be nil.
// If it is, just ignore the line."
// accessFunction() might not be called,
// but it won't explode.
var asdf = resultOfAFunctionThatReturnsAQuestionMarkValue()
asdf!.accessFunction() // "Yo, dude. I know for sure this is not nil.
// Don't bother checking first. It's cool."
// this could break if asdf if nil
// You just lied to the computer.
// (They will remember.)
