GregLeck

Optionals

Oct 5th, 2019
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 3.43 KB | None | 0 0
  1. // OPTIONALS
  2. // Make an optional value = nil
  3. var someNilValue: Int? = nil
  4.  
  5. // UNWRAPPING OPTIONALS
  6. var name: String? = nil
  7.  
  8. if let unwrapped = name {
  9.     print("\(unwrapped.count) letters")
  10. } else {
  11.     print("no letters")
  12. }
  13.  
  14. // UNWRAPPING WITH GUARD LET
  15. // In this example, function has an optional parameter.
  16. // If the parameter is nil, the function will exit
  17. func receiveMessage(_ message: String?) {
  18.     guard let text = message else {
  19.         print("There's no text in the message.")
  20.         return
  21.     }
  22.    
  23.     print("Your message is: \(text)")
  24. }
  25.  
  26. receiveMessage(nil)                 // "There's no text in the message"
  27. receiveMessage("Hi!")               // "You message is: Hi!"
  28.  
  29. // Another example:
  30. func stringCounter(_ word: String?) -> Int? {
  31.     guard let word = word else {
  32.         return nil
  33.     }
  34.    
  35.     return word.count
  36. }
  37.  
  38. let myWord: String? = nil
  39.  
  40. if let myWordCount = stringCounter(myWord) {
  41.     print(myWordCount)
  42. } else {
  43.     print("You didn't send a word.")        // You didn't send a word
  44. }
  45.  
  46. // FORCE UNWRAPPING
  47. let str = "5"
  48. let num = Int(str)!
  49.  
  50. // IMPLICITELY UNWRAPPED OPTIONALS
  51. // Variable starts off as nil but we know it will eventually have a value when we need it.
  52. // Therefore, no need to use "if let" or "guard."
  53. let age: Int! = nil
  54.  
  55. // NIL COALESCING
  56. // Swift unwraps the optional and return a value if there is one, otherwise
  57. // a default value is provided
  58. func username(for id: Int) -> String? {
  59.     if id == 1 {
  60.         return "Taylor Swift"
  61.     } else {
  62.         return nil
  63.     }
  64. }
  65.  
  66. let user = username(for: 15) ?? "Anonymous"
  67. print(user)                     // "Anonymous"
  68.  
  69. // OPTIONAL CHAINING
  70. // In this example, Swift checks whether there is a value for names.first
  71. // If there isn't, it won't proceed with uppercased method.
  72. let names = ["John", "Paul", "George", "Ringo"]
  73. let beatle = names.first?.uppercased()          // "JOHN"
  74.  
  75. // OPTIONAL TRY
  76. // Code we've seen in a previous lesson (Do, Try, Catch)
  77. enum PasswordError: Error {
  78.     case obvious
  79. }
  80.  
  81. func checkPassword(_ password: String) throws -> Bool {
  82.     if password == "password" {
  83.         throw PasswordError.obvious
  84.     }
  85.  
  86.     return true
  87. }
  88.  
  89. // Using try? -- changes throwing functions into fuction that return an optional
  90. if let result = try? checkPassword("password") {
  91.     print("Result was \(result)")
  92. } else {
  93.     print("d'oh!")
  94. }
  95.  
  96. // try! -- when you know for sure that function will not fail.
  97. //          If it does throw and error, your code will crash
  98. try! checkPassword("sekrit")
  99. print("no error thrown!")
  100.  
  101.  
  102. // FAILABLE INITIALIZERS
  103. // Use init? rather than init()
  104. // If the condition is met, the struct will return an optional
  105. // that you can unwrap in the manner you want.
  106. struct Person {
  107.     var id: String
  108.    
  109.     init?(id: String) {
  110.         if id.count == 9 {
  111.             self.id = id
  112.         } else {
  113.             return nil
  114.         }
  115.     }
  116. }
  117.  
  118. // TYPECASTING
  119. // In this example, both Fish and Dog inherit from Aninal()
  120. class Animal { }
  121. class Fish: Animal { }
  122.  
  123. class Dog: Animal {
  124.     func makeNoise() {
  125.         print("Woof!")
  126.     }
  127. }
  128.  
  129. // Create array of pets:
  130. let pets = [Fish(), Dog(), Fish(), Dog()]
  131.  
  132. // Using a for loop, we check to see which pet is of the Dog class
  133. // "as?" will return an optional, either 1) nil if the typecast failed
  134. // or 2) the converted type
  135. for pet in pets {
  136.     if let dog = pet as? Dog {
  137.         dog.makeNoise()
  138.     }
  139. }
Advertisement
Add Comment
Please, Sign In to add comment