Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // STRUCTS - PART II
- // Structs come with their own memberwise initializer
- // but we can provide our own init() method
- // to initialize all stored properties
- struct User {
- var username: String
- init() {
- username = "Anonymous"
- print("We have a new user!")
- }
- }
- var person = User()
- person.username // "Anonymous"
- person.username = "leck"
- print(person.username) // "leck"
- // SELF: REFERRING TO THE CURRENT INSTANCE
- // Useful when a property and init parameter share the same name
- struct Car {
- var color: String
- init(color: String) {
- self.color = color
- }
- }
- let buick = Car(color: "red")
- print(buick.color) // "red"
- // LAZY PROPERTIES
- // Property is only created when it is first accessed
- struct FamilyTree {
- init() {
- print("Creating family tree")
- }
- }
- struct Person {
- var name: String
- lazy var familyTree = FamilyTree() // property not created unless accessed
- init(name: String) {
- self.name = name
- }
- }
- var ed = Person(name: "ed")
- // Access familyTree property to see message:
- ed.familyTree // "Creating family tree"
- // ACCESS CONTROL
- // Use "private" to restict access to properties and functions
- // within a given struct
- // Struct's memberwise contructor not available with private properties
- struct PrivateData {
- var name: String
- private var idNumber: Int
- init(name: String, idNumber: Int) {
- self.name = name
- self.idNumber = idNumber
- }
- func printTheId() {
- print("The id is \(idNumber)")
- }
- private func privateMessage() {
- print("The id is \(idNumber)")
- }
- }
- let john = PrivateData(name: "John", idNumber: 9384092)
- john.name // "John"
- // john.idNumber // Not accessible
- john.printTheId() // "The id is 9384092"
- // john.privateMessage() // Not accessible
- // STATIC PROPERTIES AND METHODS
- struct StaticExample {
- var name: String
- static var quote = "It's not who you are underneath, but what you do that defines you."
- init(name: String) {
- self.name = name
- }
- }
- let bruceWayne = StaticExample(name: "Batman")
- bruceWayne.name // "Batman"
- StaticExample.quote // "It's not who..."
Advertisement
Add Comment
Please, Sign In to add comment