Swift Structures
Explore how to declare and utilize Swift structures, including their syntax and behavior. Understand the fundamental distinctions between value type structures and reference type classes, including copying behavior and method passing. Learn when to use structures versus classes in Swift app development.
We'll cover the following...
Having covered Swift classes in the preceding lessons, this lesson will introduce the use of structures in Swift. Although at first glance, structures and classes look similar. But some important differences need to be understood when deciding which to use. This lesson will outline how to declare and use structures, explore the differences between structures and classes, and introduce the concepts of value and reference types.
An overview of Swift structures
As with classes, structures form the basis of object-oriented programming and provide a way to encapsulate data and functionality into reusable instances. Structure declarations resemble classes with the exception that the struct keyword is used in place of the class keyword. The following code, for example, declares a simple structure consisting of a String variable, initializer, and method:
struct SampleStruct {
var name: String
init(name: String) {
self.name = name
}
func buildHelloMsg() {
"Hello " + name
}
}
Consider the above structure declaration in comparison to the equivalent class declaration:
class SampleClass {
var name: String
init(name: String) {
...