Structures
Model everyday objects using structures!
StartKey Concepts
Review core concepts you need to learn to master this subject
Structure Creation
Default Property Values
Structure Instance Creation
Checking Type
init()
Method
Structure Methods
Mutating Methods
Structure Creation
Structure Creation
struct Building {
var address: String
var floors: Int
init(address: String, floors: Int, color: String) {
self.address = address
self.floors = floors
}
}
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.
Structures
Lesson 1 of 1
- 1As developers, we create programs and applications to solve problems — problems that we encounter on a daily basis that usually stem from everyday life. More often than not, these problems ar…
- 2With structures, we can create our own data type and use them to model everyday objects with their own unique characteristics. Here’s the basic syntax for a structure: struct Name { Properties }…
- 3Now that we know how to create a structure we should also know how to create customized instances of that structure. But, what if we’re creating a lot of instances, do we really need to customize e…
- 4Instances are how we create individual objects using a structure. In the previous exercise’s example, we created a structure to model dogs: struct Dog { var age = 0 var isGood = true } In …
- 5We’ve created models of real-life objects using instances and now let’s find out how to customize them. Since instances of a struct can have different property values, we should know how to access …
- 6In the previous exercise, we’ve supplied our instances’ properties with default values. However, if we know that our struct instances vary a lot from one to another, we can include an init() method…
- 7In the previous exercise, we’ve explicitly provided an init() method inside our struct. Structures also come with a built-in memberwise initializer that can be used to assign values upon instance…
- 8In addition to the init() method, we can also provide our structs with custom methods that instances can call. These instance methods are created like a normal function but within the scope of th…
- 9While a mutating method may sound like a term out of a mad scientist’s lab, it’s actually how we change an instance’s properties using an instance method. To do so, we need the mutating keyword: …
- 11In Swift, data types can be value types or reference types. This means that different data types are stored and accessed in different ways. Structures are value types, this means every time an …
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory