Day 9 – Structs Part Two

[cc_swift width=”100%” height=”100%”] // initializers // by default, structs use an initializer which requires us, at call time, to // provide values for each property. However we can create our own. struct User { var username: String init() { username = “Anonymous” print(“Creating a new user…”) } } // important to note: do not write methods before the initializer, and make // sure all properties have a value by the time the initializer ends. var myUser = User() myUser.username myUser.username = “newUsername” // “self” // the “self” keyword refers to the instance of the struct currently being used struct Car { var model: String init(model: String) { print(“This car’s model is \(model)”) self.model = model // model is the parameter, self.model the property } } var myCar = Car(model: “Tucson”) // lazy properties // there might be some properties of a struct that take a lot of memory, or // processing power. for this reason, if we add the keyword ‘lazy’ swift will // only create that property when it’s first accessed. struct Dog { var name: String lazy var car = Car(model: “Doggydog”) init(name: String) { = name } } // static properties and methods // so far, all properties and methods belonged to the particular instances of // the struct made. But what about making one for the struct itself, shared // among all instances? that’s what static properties are struct Student { static var classSize = 0 var name: String init(name: String) { = name Student.classSize += 1 } } // given it’s static we need to call it using Student.classSize (it belongs to // the struct) // private properties // we can make it so that properties of a struct cannot be read from outside the // struct’s methods itself. struct Person { private var id: String init(id: String) { = id } func identify() -> String { return “This person’s ID is \(id).” } } var myPerson = Person(id: “12345”) myPerson.identify() [/cc_swift]

Leave a Comment