Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func getHaterStatus(weather: String) -> String? {
- if weather == "sunny" {
- return nil
- } else {
- return "Hate"
- }
- }
- // For the code to work, the status variable must be marked as optional
- // i.e., var status: String?
- // Or, type inference must be used as in the below example:
- var status = getHaterStatus(weather: "rainy") // status is an optional
- // The function below accepts a String but NOT an optional String.
- // So, status (an optional) couldn't be passed into it.)
- func takeHaterAction(status: String) {
- if status == "Hate" {
- print("Hating")
- }
- }
- // To ensure that takeHaterAction() receives a non-optional,'
- // we use "if let."
- // If getHaterStatus returns a value that is not nil,
- // haterStatus (a non-optional) can be passed to takeHaterAction()
- if let haterStatus = getHaterStatus(weather: "rainy") {
- takeHaterAction(status: haterStatus)
- }
- // NIL COALESCING
- // newStatus is a non-optional because it will receive a value.
- // (In this ex. getHaterStatus returns nil so newStatus = "None of..."
- let newStatus = getHaterStatus(weather: "sunny") ?? "None of your business"
Advertisement
Add Comment
Please, Sign In to add comment