Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. //
  2. // Swift 3, Optional
  3. //
  4.  
  5. // Defining
  6. let possibleNumber = "123"
  7. let convertedNumber = possibleNumber.toInt() // convertedNumber is inferred to be of type 'Int?' or 'Optional<Int>"
  8.  
  9.  
  10. // Nil
  11. var serverResponseCode: Int? = 404 // serverResponseCode contains an actual Int value of 404
  12. serverResponseCode = nil // serverResponseCode now contains no value
  13.  
  14.  
  15. // if Statements and Forced Unwrapping
  16. if convertedNumber != nil {
  17. println("convertedNumber contains some integer value.")
  18. }
  19. // prints "convertedNumber contains some integer value."
  20.  
  21.  
  22. // Optional Binding
  23. if let actualNumber = possibleNumber.toInt() {
  24. println("\'\(possibleNumber)\' has an integer value of \(actualNumber)")
  25. } else {
  26. println("\'\(possibleNumber)\' could not be converted to an integer")
  27. }
  28. // prints "'123' has an integer value of 123"
  29.  
  30.  
  31. // Implicitly Unwrapped Optionals
  32. let possibleString: String? = "An optional string."
  33. let forcedString: String = possibleString! // requires an exclamation mark
  34.  
  35. let assumedString: String! = "An implicitly unwrapped optional string."
  36. let implicitString: String = assumedString // no need for an exclamation mark
  37.  
  38.  
  39. // Nil-Coalescing Operator (Optional<AType> ?? AType)
  40. let notOptionalString = possibleString ?? "default value"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement