NEW! Master Swift design patterns with my latest book! >>

What’s the difference between a class and a struct?

Paul Hudson       @twostraws

Classes and structures (structs) are so similar in Swift that it's easy to get them confused at first, but actually there are some important underlying differences:

  • A struct cannot inherit from another kind of struct, whereas classes can build on other classes.
  • You can change the type of an object at runtime using typecasting. Structs cannot have inheritance, so have only one type.
  • If you point two variables at the same struct, they have their own independent copy of the data. With objects, they both point at the same variable.

That last point is particularly important: with a struct you know your data is fixed in place, like an integer or other value. This means if you pass your struct into a function, you know it's not going to get modified.

Available from iOS 7.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Become a Swift expert

I wrote a book called Pro Swift that's dedicated to helping you master the Swift language, and it includes seven hours of video demonstrating each technique!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>