GregLeck

More Optionals

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