NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Summary: Structs

Paul Hudson    @twostraws   

Updated for Xcode 14.2

Structs are used almost everywhere in Swift: String, Int, Double, Array and even Bool are all implemented as structs, and now you can recognize that a function such as isMultiple(of:) is really a method belonging to Int.

Let’s recap what else we learned:

  • You can create your own structs by writing struct, giving it a name, then placing the struct’s code inside braces.
  • Structs can have variable and constants (known as properties) and functions (known as methods)
  • If a method tries to modify properties of its struct, you must mark it as mutating.
  • You can store properties in memory, or create computed properties that calculate a value every time they are accessed.
  • We can attach didSet and willSet property observers to properties inside a struct, which is helpful when we need to be sure that some code is always executed when the property changes.
  • Initializers are a bit like specialized functions, and Swift generates one for all structs using their property names.
  • You can create your own custom initializers if you want, but you must always make sure all properties in your struct have a value by the time the initializer finishes, and before you call any other methods.
  • We can use access to mark any properties and methods as being available or unavailable externally, as needed.
  • It’s possible to attach a property or methods directly to a struct, so you can use them without creating an instance of the struct.
Hacking with Swift is sponsored by Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.