Day 8 – Structs Part One

[cc_swift width=”100%” height=”100%”] // structs // a struct is a way in which you can create your own type in Swift. Structs can have their own variables, constants, methods, etc. // important to note that variables in a struct are called “properties” of the struct. struct Sport { var name: String } struct Car { var make: String var year: Int var model: String var isElectric: Bool var engineType: String { // computed property if isElectric { return “This \(make) \(model)’s engine is electric!” } else { return “This \(make) \(model)’s engine burns dead dinosaurs.” } } func returnCarTax() -> Int { return year * 1111 } mutating func switchEngine() { // mutating methods can change a struct’s parameters if isElectric { isElectric = false } else { isElectric = true } } } var myNiceCar = Car(make: “Hyundai”, year: 2016, model: “Tucson”, isElectric: false) var sport = Sport(name: “Tennis”) print(myNiceCar.engineType) // property observers struct Progress { var task: String var amount: Int { didSet { // when amount is changed, {this} is run print(“\(task) is now \(amount)% complete.”) } } } var myProgress = Progress(task: “Listening”, amount: 10) myProgress.amount = 20 myNiceCar.switchEngine() print(myNiceCar.engineType) print(myNiceCar.returnCarTax()) [/cc_swift]

Leave a Reply

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