Swift Tour Summary (3), swifttour
About Optional Control Flow
If let constantName = someOptional {
Statements
}
If the Optional is nil, if is not entered; otherwise, the execution and constantName are the value of the Optional.
Example:
If let actualNumber = possibleNumber. toInt (){
Println ("\ (possibleNumber) has an integer value of \ (actualNumber )")
} Else {
Println ("\ (possibleNumber) cocould not be converted to an integer ")
}
// Prints "123 has an integer value of 123"
About nil
Optional can be assigned a value of nil.
For example:
Var serverResponseCode: Int? = 404
ServerResponseCode = nil
Var surveyAnswer: String?
// SurveyAnswer is automatically set to nil
Expansion of optional: Implicitly Unwrapped Optionals
Sometimes, an optional will be safe after the first assignment, and nil check is not required.
Definition: String! Instead of String?
Example:
Let possibleString: String? = "An optional string ."
Println (possibleString !) // Requires an exclamation mark to access this value
// Prints "An optional string ."
Let assumedString: String! = "An implicitly unwrapped optional string ."
Println (assumedString) // no exclamation mark is needed to access its value
// Prints "An implicitly unwrapped optional string ."
For this special type (IUO), general optional usage is applicable:
If assumedString {
Println (assumedString)
}
Assertions-debugging
Let age =-3
Assert (age> = 0, "A person's age cannot be less than zero ")
// Assertion trigger