GregLeck

More on optionals

Oct 6th, 2019
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.15 KB | None | 0 0
  1. // MORE ON OPTIONALS
  2. func getHaterStatus(weather: String) -> String? {
  3.     if weather == "sunny" {
  4.         return nil
  5.     } else {
  6.         return "Hate"
  7.     }
  8. }
  9.  
  10. // For the code to work, the status variable must be marked as optional
  11. // i.e., var status: String?
  12. // Or, type inference must be used as in the below example:
  13. var status = getHaterStatus(weather: "rainy") // status is an optional
  14.  
  15. // The function below accepts a String but NOT an optional String.
  16. // So, status (an optional) couldn't be passed into it.)
  17. func takeHaterAction(status: String) {
  18.     if status == "Hate" {
  19.         print("Hating")
  20.     }
  21. }
  22.  
  23. // To ensure that takeHaterAction() receives a non-optional,'
  24. // we use "if let."
  25. // If getHaterStatus returns a value that is not nil,
  26. // haterStatus (a non-optional) can be passed to takeHaterAction()
  27. if let haterStatus = getHaterStatus(weather: "rainy") {
  28.     takeHaterAction(status: haterStatus)
  29. }
  30.  
  31. // NIL COALESCING
  32. // newStatus is a non-optional because it will receive a value.
  33. // (In this ex. getHaterStatus returns nil so newStatus = "None of..."
  34. let newStatus = getHaterStatus(weather: "sunny") ?? "None of your business"
Advertisement
Add Comment
Please, Sign In to add comment