Structures, or structs, are used to programmatically represent a real-life object in code. Structures are created with the struct
keyword followed by its name and then body containing its properties and methods.
struct Building {var address: Stringvar floors: Intinit(address: String, floors: Int, color: String) {self.address = addressself.floors = floors}}
A structure’s properties can have preassigned default values to avoid assigning values during initialization. Optionally, these property’s values can still be assigned a value during initialization.
struct Car {var numOfWheels = 4var topSpeed = 80}var reliantRobin = Car(numOfWheels: 3)print(reliantRobin.numOfWheels) // Prints: 3print(reliantRobin.topSpeed) // Prints: 80
A new instance of a structure is created by using the name of the structure with parentheses ()
and any necessary arguments.
struct Person {var name: Stringvar age: Intinit(name: String, age: Int) {self.name = nameself.age = age}}// Instance of Person:var morty = Person(name: "Morty", age: 14)
The built-in function type(of:)
accepts an argument and returns the type of the argument passed.
print(type(of: "abc")) // Prints: Stringprint(type(of: 123)) // Prints: 123
init()
MethodStructures can have an init()
method to initialize values to an instance’s properties. Unlike other methods, The init()
method does not need the func
keyword. In its body, the self
keyword is used to reference the actual instance of the structure.
struct TV {var screenSize: Intvar displayType: Stringinit(screenSize: Int, displayType: String) {self.screenSize = screenSizeself.displayType = displayType}}var newTV = TV(screenSize: 65, displayType: "LED")
Methods are like functions that are specifically called on an instance. To call the method, an instance is appended with the method name using dot notation followed by parentheses that include any necessary arguments.
struct Dog {func bark() {print("Woof")}}let fido = Dog()fido.bark() // Prints: Woof
Structure methods declared with the mutating
keyword allow the method to affect an instance’s own properties.
struct Menu {var menuItems = ["Fries", "Burgers"]mutating func addToMenu(dish: String) {self.menuItems.append(dish)}}var dinerMenu = Menu()dinerMenu.addToMenu(dish: "Toast")print(dinerMenu.menuItems)// Prints: ["Fries", "Burgers", "Toast"]