Learn SwiftUI (Day 10/10)

RMAG news

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: 199)
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *