TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Summary: Structs

Paul Hudson    @twostraws   

Updated for Xcode 15

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 Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

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

BUY OUR BOOKS
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.9/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.