Optionals

nil
// You set an optional variable to a valueless state by assigning it the special value nil:
var serverResponseCode: Int? = 404
// serverResponseCode contains an actual Int value of 404
serverResponseCode = nil
// serverResponseCode now contains no value
var surveyAnswer: String?
// surveyAnswer is automatically set to nil
var wordCount : [String: Int] = [:]
if wordCount["Hello"] != nil {
    // do something there
    wordCount["Hello"] ! += 1 // put "!" behind it because we know it exist
}

use exclamation mark to get content of optional

var dog : String? = "Miki"
print(dog)     // "Optional("Miki")\n"
print(dog!)    //  "Miki\n" 

// Optional Binding
if let theDog = dog {
    print(theDog)
}
###### NOTE
`nil` cannot be used with nonoptional constants and variables. If a constant or variable in your code needs to work with the absence of a value under certain conditions, always declare it as an optional value of the appropriate type.
###### Reference:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309

你可能感兴趣的:(Optionals)