NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

Summary: Structs

Paul Hudson    @twostraws   

Updated for Xcode 13.3

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 RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

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

Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.