DEV Community

BC
BC

Posted on

Learn SwiftUI (Day 10/10)

Swift

  • define struct
  • computed property
  • getter and setter
  • property observer: willSet, didSet
  • customize init function
import Cocoa

// ## Define struct

struct Employee {
    let name: String
    var vacationRemaining: Int

    mutating func takeVacation(days: Int) {
        if vacationRemaining > days {
            vacationRemaining -= days
            print("I'm going on vacation!")
            print("Days remaining: \(vacationRemaining)")
        } else {
            print("Oops! There aren't enough days remaining.")
        }
    }
}
// ## Computed Properties with getter and setter
struct Employee2 {
    let name: String
    var vacationAllocated = 14
    var vacationTaken = 0

    var vacationRemaining: Int {
        // getter
        get {
            vacationAllocated - vacationTaken
        }
        // setter -> even we have a setter here, no `mutating` needs to be added
        set {
            vacationAllocated = vacationTaken + newValue
        }
    }
}

// ## Property observers
// willSet and didSet
struct App {
    var contacts = [String]() {
        // newValue and oldValue are built-in variable in observers
        willSet {
            print("Current value is: \(contacts)")
            print("New value will be: \(newValue)")
        }

        didSet {
            print("There are now \(contacts.count) contacts.")
            print("Old value was \(oldValue)")
        }
    }
}

// ## custom initializers
// explicitly define `init` function - no `func` needed, and you can use `self.`

struct Player {
    let name: String
    let number: Int

    init(name: String) {
        self.name = name
        number = Int.random(in: 1...99)
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)