Lesson 52Structs
Properties
Types of Properties
Structs can have different types of properties: stored, computed, observed, and type properties!
Property Types
StoredStore actual values (var/let)
ComputedCalculate values on demand
ObservedRun code when value changes
LazyInitialize when first accessed
Type (static)Shared across all instances
Computed Property Syntax
var name: Type {
get { // return value }
set { // use newValue }
}
get { // return value }
set { // use newValue }
}
Property Observers
willSet
Called before value changes
Access: newValuedidSet
Called after value changes
Access: oldValuemain.swift
// STRUCT PROPERTIES
// Properties are variables/constants that belong to a struct
// STORED PROPERTIES
struct Rectangle {
var width: Double // Stored property (variable)
var height: Double // Stored property (variable)
let color: String // Stored property (constant)
}
var rect = Rectangle(width: 10, height: 5, color: "blue")
rect.width = 15 // OK - var can change
// rect.color = "red" // ERROR - let cannot change
// COMPUTED PROPERTIES
struct Circle {
var radius: Double
// Computed property (read-only)
var diameter: Double {
radius * 2
}
var area: Double {
Double.pi * radius * radius
}
var circumference: Double {
2 * Double.pi * radius
}
}
let circle = Circle(radius: 5)
print(circle.diameter) // 10.0
print(circle.area) // 78.54...
// GETTER AND SETTER
struct Temperature {
var celsius: Double
var fahrenheit: Double {
get {
celsius * 9/5 + 32
}
set {
celsius = (newValue - 32) * 5/9
}
}
}
var temp = Temperature(celsius: 0)
print(temp.fahrenheit) // 32.0
temp.fahrenheit = 212
print(temp.celsius) // 100.0
// PROPERTY OBSERVERS
struct Player {
var score: Int = 0 {
willSet {
print("Score will change to \(newValue)")
}
didSet {
print("Score changed from \(oldValue)")
if score > oldValue {
print("Great job! +\(score - oldValue) points!")
}
}
}
}
var player = Player()
player.score = 10
// LAZY PROPERTIES
struct DataManager {
var filename: String
lazy var data: [String] = {
print("Loading data...")
return ["item1", "item2", "item3"]
}()
}
var manager = DataManager(filename: "data.txt")
print("Manager created") // data NOT loaded yet
print(manager.data) // NOW data is loaded
// TYPE PROPERTIES (Static)
struct AppConfig {
static let appName = "SwiftApp"
static var version = "1.0.0"
static var userCount = 0
}
print(AppConfig.appName) // SwiftApp
AppConfig.userCount += 1
print(AppConfig.userCount) // 1Try It Yourself!
Create a BankAccount struct with balance and a computed property isOverdrawn!