Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 28, 2022 02:42 pm GMT

Day 10-11: 100 Days of SwiftUI

Structs, computed properties, and property observers

https://www.hackingwithswift.com/100/swiftui/10

Structs

Like classes and enums, structs are way to implement a custom type in Swift, complete with their own variables and their own functions.

struct Album {    let title: String    let artist: String    let year: Int    func printSummary() {        print("\(title) (\(year)) by \(artist)")    }}let red = Album(title: "Red", artist: "Taylor Swift", year: 2012)print(red.title)red.printSummary()

Mutating functions

If you want to allow functions to change the struct's data, we can add the mutating keyword to any function.

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

Structs can have two kinds of property: a stored property is a variable or constant that holds a piece of data inside an instance of the struct, and a computed property calculates the value of the property dynamically every time its accessed.

struct Employee {    let name: String    var vacationAllocated = 14    var vacationTaken = 0    var vacationRemaining: Int {        get {        vacationAllocated - vacationTaken        }        set {            vacationAllocated = vacationTaken + newValue        }    }}var archer = Employee(name: "Sterling Archer", vacationAllocated: 14)archer.vacationTaken += 4archer.vacationRemaining = 5print(archer.vacationAllocated)

Getters denoted by get reads and computes data, while setters denoted by set writes/updates the data directly based on the value the user was trying to assign to the property, using the name newValue.

Property observers

Property observers are blocks of code that run when properties changed. A didSet observer to run when the property just changed, and a willSet observer to run before the property changed.

struct App {    var contacts = [String]() {        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)")        }    }}var app = App()app.contacts.append("Adrian E")app.contacts.append("Allen W")

Custom initializer

To create custom initializer, use the init function without the func keyword:

struct Player {    let name: String    let number: Int    init(name: String) {        self.name = name        number = Int.random(in: 1...99)    }}let player = Player(name: "Megan R")print(player.number)

Access control, static properties and methods, and checkpoint 6

https://www.hackingwithswift.com/100/swiftui/11

Access control

Access control controls how struct's properties and methods can be accessed from outside the struct.

Swift offers several levels of access control.

  • public access - cannot be used outside the struct
  • fileprivate access - cannot be used outside the current file
  • private access - usable anywhere
  • private(set) access - can be read anywhere, but only the struct's method can write to it.
struct BankAccount {    private var funds = 0    mutating func deposit(amount: Int) {        funds += amount    }    mutating func withdraw(amount: Int) -> Bool {        if funds > amount {            funds -= amount            return true        } else {            return false        }    }}

Static properties and methods

If you want to use property or method directly, i.e. storing fixed data that needs to be accessed in various places, use static on the properties and methods.

struct AppData {    static let version = "1.3 beta 2"    static let saveFilename = "settings.json"    static let homeURL = "https://www.hackingwithswift.com"}print(AppData.version)

Checkpoint 6

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 somehow?

Solution here


Original Link: https://dev.to/johnkevinlosito/day-10-11-100-days-of-swiftui-1d8l

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To