Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Swift 3, Optional
- //
- // Defining
- let possibleNumber = "123"
- let convertedNumber = possibleNumber.toInt() // convertedNumber is inferred to be of type 'Int?' or 'Optional<Int>"
- // Nil
- var serverResponseCode: Int? = 404 // serverResponseCode contains an actual Int value of 404
- serverResponseCode = nil // serverResponseCode now contains no value
- // if Statements and Forced Unwrapping
- if convertedNumber != nil {
- println("convertedNumber contains some integer value.")
- }
- // prints "convertedNumber contains some integer value."
- // Optional Binding
- if let actualNumber = possibleNumber.toInt() {
- println("\'\(possibleNumber)\' has an integer value of \(actualNumber)")
- } else {
- println("\'\(possibleNumber)\' could not be converted to an integer")
- }
- // prints "'123' has an integer value of 123"
- // Implicitly Unwrapped Optionals
- let possibleString: String? = "An optional string."
- let forcedString: String = possibleString! // requires an exclamation mark
- let assumedString: String! = "An implicitly unwrapped optional string."
- let implicitString: String = assumedString // no need for an exclamation mark
- // Nil-Coalescing Operator (Optional<AType> ?? AType)
- let notOptionalString = possibleString ?? "default value"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement