Updated for Xcode 14.2
Swift uses structs for storing most of its data types, including String
, Int
, Double
, and Array
, but there is another way to create custom data types called classes. These have many things in common with structs, but are different in key places.
First, the things that classes and structs have in common include:
However, classes differ from structs in five key places:
On the surface those probably seem fairly random, and there’s a good chance you’re probably wondering why classes are even needed when we already have structs.
However, SwiftUI uses classes extensively, mainly for point 3: all copies of a class share the same data. This means many parts of your app can share the same information, so that if the user changed their name in one screen all the other screens would automatically update to reflect that change.
The other points matter, but are of varying use:
Before we’re done, let’s look at just a tiny slice of code that creates and uses a class:
class Game {
var score = 0 {
didSet {
print("Score is now \(score)")
}
}
}
var newGame = Game()
newGame.score += 10
Yes, the only difference between that and a struct is that it was created using class
rather than struct
– everything else is identical. That might make classes seem redundant, but trust me: all five of their differences are important.
I’ll be going into more detail on the five differences between classes and structs in the following chapters, but right now the most important thing to know is this: structs are important, and so are classes – you will need both when using SwiftUI.
SPONSORED Thorough mobile testing hasn’t been efficient testing. With Waldo Sessions, it can be! Test early, test often, test directly in your browser and share the replay with your team.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.