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