DEV Community

BC
BC

Posted on

Learn SwiftUI (Day 5/100)

Swift

  • if - else
  • if - else if - else
  • switch - case - default - fallthrough
  • ternary
import Cocoa

// ## Conditions
// if
var username = ""
if username.count == 0 {
    print("empty")
} else {
    print("not empty")
}
username = "john doe"
if username.isEmpty {
    print("empty")
} else {
    print("not empty")
}

// if - else if - else
let a = false
let b = true
if a {
    print("Code to run if a is true")
} else if b {
    print("Code to run if a is false but b is true")
} else {
    print("Code to run if both a and b are false")
}

// && - and, || - or
/*
 if temp > 20 && temp < 30 {}
 if userAge >= 18 || hasParentalConsent == true {}
 */

// ## switch - case
let place = "Metropolis"

// You must list all outcomes as case statements or use default.
switch place {
case "Gotham":
    print("You're Batman!")
case "Mega-City One":
    print("You're Judge Dredd!")
case "Wakanda":
    print("You're Black Panther!")
default:
    print("Who are you?")
}

/*
 Remember: Swift checks its cases in order and runs the first one that matches. 
 If you place default before any other case, that case is useless
 because it will never be matched and Swift will refuse to build your code.

 Second, if you explicitly want Swift to carry on executing subsequent cases, 
 use `fallthrough`. This is not commonly used.
 */

let day = 5
print("My true love gave to me…")

switch day {
case 5:
    print("5 golden rings")
    fallthrough
case 4:
    print("4 calling birds")
    fallthrough
case 3:
    print("3 French hens")
    fallthrough
case 2:
    print("2 turtle doves")
    fallthrough
default:
    print("A partridge in a pear tree")
}

// ## Ternary
let age = 18
let canVote = age >= 18 ? "Yes" : "No"
print(canVote)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)