Learn SwiftUI (Day 11/100)
BC
Posted on May 1, 2024
Swift
- private / fileprivate / public
- static, self and Self
import Cocoa
// ## private
struct BankAccount {
private var funds = 0
}
/*
* Use private for “don’t let anything outside the struct use this.”
* Use private(set) for “let anyone read this property, but only let my methods write it.”
* Use fileprivate for “don’t let anything outside the current file use this.”
* Use public for “let anyone, anywhere use this.”
*/
// ## static variable and function
struct School {
static var studentCount = 0
static func add(student: String) {
print("\(student) joined the school.")
studentCount += 1
}
}
// ## self and Self
/*
To access static code from non-static code,
always use your type’s name such as School.studentCount.
You can also use Self to refer to the current type.
*/
// ## singleton
struct Employee {
let username: String
let password: String
static let example = Employee(username: "abc", password: "xyz")
}
// ## Check point
/*
create a struct to store information about a car,
including its model, number of seats, and current gear,
then add a method to change gears up or down.
Have a think about variables and access control:
what data should be a variable rather than a constant,
and what data should be exposed publicly?
Should the gear-changing method validate its input
*/
struct Car {
let model: String
let numberOfSeats: Int
private var currentGear: Int
init(model: String, numberOfSeats: Int) {
self.model = model
self.numberOfSeats = numberOfSeats
self.currentGear = 0
}
mutating func gearUp() -> Bool {
if self.currentGear == 6 {
return false
}
self.currentGear += 1
return true
}
mutating func gearDown() -> Bool {
if self.currentGear == 0 {
return false
}
self.currentGear -= 1
return true
}
}
💖 💪 🙅 🚩
BC
Posted on May 1, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
nvidia Running Ollama and Open WebUI containers on Jetson Nano with GPU Acceleration: A Complete Guide
November 30, 2024