100 Days of SwiftUI - Day 5

100 Days of SwiftUI - Day 5

Hello, and welcome to day 5. If you're jumping in here, head on over to: https://blog.grayw.co.uk/tag/100daysofswiftui/

Follow along from the beginning (or jump in wherever you like, whatever nibbles your biscuit).

Workspace

Today we'll be heading back over to the MacBook and Xcode, even though I certainly prefer the feel of Swift Playgrounds 4 so far.

Day 5 - Overview

Today we're going to be looking at if/else/else if, and a few other bits and pieces.

Check if a condition is true or false

//
// How to check a true/false condition
//

var someCondition = true

if someCondition {
    print("Do Something")
}

let score = 85

if score > 80 { // > is a comparison operator is score greater than 80
    print("You pass!")
}

let speed = 88
let percentage = 85
let age = 18

if speed >= 88 {
    print("Where we're going, we don't need roads.")
}

if percentage < 85 {
    print("Sorry, you failed the test")
}

if age >= 18 {
    print("You're eligible to vote")
}

// The comparison operators also work well with strings

let ourName = "Dave Lister"
let friendName = "Arnold Rimmer"

if ourName < friendName {
    print("It's \(ourName) vs \(friendName)")
}

if ourName > friendName {
    print("It's \(friendName) vs \(ourName)")
}


//

var numbers = [1, 2, 3]
numbers.append(4)

if numbers.count > 3 {
    numbers.remove(at: 0)
}

print(numbers)

// We can also check equality

let country = "Canada"

if country == "Australia" {
    print("G'day!")
}

let name = "Swifty"

if name != "Anonymous" {
    print("Welcome, \(name)")
}


var username = "swifty22"

if username == "" {
    username = "Anonymous"
}

print("Welcome, \(username)")

// Not an efficient way of doing it. If the value has hundreds of characters, it will count them all.
if username.count == 0 {
    username = "Anonymous"
}

// A more efficient, and easier way is to use isEmpty

if username.isEmpty {
    username = "Anonymous"
}

// Comparisons can also be done on enums (done on order in case list)
enum Sizes: Comparable {
    case small
    case medium
    case large
}

let first = Sizes.small
let second = Sizes.large

print(first < second)

How to check multiple conditions

//
// How to check multiple conditions
//
if someCondition {
    print("This will run if the condition is true")
} else {
    print("This will run if the condition is false")
}

// We can use else if's - but this can make code more complex
let a: Bool = true
let b: Bool = false

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")
}

// We can use && (and)
let temp = 25

if temp > 20 && temp < 30 {
    print("It's a nice day.")
}

let userAge = 14
let hasParentalConsent = true

// We can use || (or)
if userAge >= 18 || hasParentalConsent {
    print("You can buy the game")
}

enum transportOptions {
    case airplane, helicopter, bike, car, escooter
}

let transport = transportOptions.bike

if transport == .airplane || transport == .helicopter {
    print("Let's fly!")
} else if transport == .bike {
    print("I hope there's a bike path")
} else if transport == .car {
    print("Time to get stuck in traffic")
} else {
    print("I'm going to hire a scooter now")
}

// If mixing && and || - it's good practice to use parentheses to make the result clearer
if (isOwner == true && isEditingEnabled) || isAdmin == true {
    print("You can delete this post")
}
  • Conditions Review Test: 12/12
  • Combining Conditions Review Test: 12/12

How to use switch statements to check multiple conditions

When should I use switch or if?

  • switch statements must be exhaustive, so we must use a case block for every possible value to check, or have a default case (if using an enum, you don’t need default). So you may miss a case while using if/else
What happens if your switch statement isn't exhaustive, or contains a duplicate case
  • When using switch to check a value for multiple possible results, that value will only be read once. If will read it multiple times.
enum Weather {
    case sun, rain, wind, snow, unknown
}

let forcast = Weather.sun

// Using Switch to check conditions
// By using a switch - Swift knows that we need to check all possible cases (exhaustive), and there can't be duplicates
switch forcast {
case .sun:
    print("It should be a nice day")
case .rain:
    print("Pack an umbrella")
case .wind:
    print("Wear something warm")
case .snow:
    print("School is cancelled")
case .unknown:
    print("Our forcast generator is broken")
}

// We can use a default case to avoid trying to achieve the impossible of coming up with every single possible match

let place = "Metropolis"

switch place {
case "Gotham":
    print("You're Batman!")
case "Mega-City One":
    print("You're Judge Dredd")
default:
    print("Who are you?")
}

// Fallthrough can be used to allow multiple cases to be run but is rarely used in Swift

let day = 5
print("My true love game 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")
}

Switch Statements Review Test: 6/6

How to use the ternary conditional operator for quick tests

The ternary operator lets us choose from one of two results based on a condition in a concise way.

It has become important in SwiftUI, so is a key thing to know about.

// 2 + 5 - The + is a binary operator (they operate on two pieces of input)
// The is a ternary operator (it operates on three pieces of input). Let's us check a condition and then send back one value, or another value depending on the condition

let age = 18
let canVote = age >= 18 ? "Yes" : "No"
print(canVote)

// age >= 18 - The condition to be checked
// If true - Send back yes
// If false - Send back no

// Similar condensed form of if/else
// W T F - What? / True / False @scottmichaud

let hour = 23
print(hour < 12 ? "It's before noon" : "It's after noon")

// Check an array
let names = ["Jayne", "Kayleigh", "Mal"]
let crewCount = names.isEmpty ? "No one" : "\(names.count) people"
print(crewCount)

// With an enum

enum Theme {
    case light, dark
}

// Condition can also be put in parentheses
let theme = Theme.dark
let background = (theme == .dark) ? "black" : "white"
print(background)

Ternary Operator Review Test: 12/12

Summary

Today seemed to go on forever, and I was only making notes in the editor as I went, plus a few scrap notes here and there.

I'm not sure how long I'll keep blogging about each day, as I really don't have the time to learn, and to blog. I think I'm painting myself in to a corner again. It's leaving me with no time to do anything else I'd like to do with the few hours I get in the evening.

As you can tell, today was practically a copy/paste dump from the code editor, which seems kind of pointless and boring for a reader.

I'll see how the next few days go, and make a decision.

What are your thoughts?

Show Comments