[cc_swift width=”100%” height=”100%”] // classes // (and their differences from structs // In classes, you must always create your initializer class Car { var make: String var model: String init(make: String, model: String) { self.model = model self.make = make } func showProductionCountry() { print(“This car was designed somewhere.”) } } let myCar = Car(make: “Hyundai”, model: “Tucson”) myCar.showProductionCountry() // classes can inherit from other classes class HyundaiCar: Car { init(model: String) { super.init(make: “Hyundai”, model: model) } override func showProductionCountry() { print(“This car was designed in South Korea.”) } } var myHyundaiCar = HyundaiCar(model: “Tucccon”) myHyundaiCar.showProductionCountry() // preventing the creation of child classes with “final” final class Person { var name: String var surname: String var age: Int init(name: String, surname: String, age: Int) { self.age = age self.name = name self.surname = surname } func bark() { print(“Woof”) } deinit { // run when an instance is destroyed print(“We’ve destroyed this person.”) } } // note: copying an instance does not create an instance which points to a different location in memory for _ in 1…3 { let person = Person(name: “John”, surname: “Doe”, age: 23) person.bark() } // another note: constant instances of classes can have their properties changed (if the properties are variables) class Sedan { var shape = “Ugly” let size = “Sedan” } let mySedan = Sedan() mySedan.shape = “Uglier” [/cc_swift]

Leave a Reply

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