Structure and Class in Swift

Divesh Singh
Nov 7 · 2 min read

Nowadays Swift pamper Structure instead of Class.

After Protocol Oriented Programming in Swift, Swift provides a number of features that make Structure better than classes in many circumstances.

Do you want to know why?

In Objective-C NSString is a class whereas in Swift String is Structure.

When we say swift is faster than objective-c. There are many reasons to make it fast and using Structure is one of the reason.

Performance Optimizations : Although strings in Swift have value semantics, strings use a copy-on-write strategy to store their data in a buffer. This buffer can then be shared by different copies of a string. A string’s data is only copied lazily, upon mutation, when more than one string instance is using the same buffer. Therefore, the first in any sequence of mutating operations may cost O(*n*) time and space.

Other reason is storage location:

Structure properties are stored on Stack and Class instances are stored on Heap hence, Structure is faster than a class.

Structures are preferable if they are relatively small and copyable because copying is way safer than having multiple references to the same instance as happens with classes.

While using Structure, you don’t need to worried about the any kind of modification on your variable in multithreaded environment. As everyone has own copy of the object.

Sample code for to describe value and reference type :

Difference between Structure and class

  1. Classes have Inheritance which allows one class to inherit.

2. Structures are value types it copy same memory into another location, and classes are reference type used same memory.

3 Structure properties are stored on Stack and Class instances are stored on Heap hence, Structure is faster than a class.

4. Structure gets a default initializer automatically whereas in Class, we have to initialize.

5. Structure is thread safe by default. In Case of Class we need to do some extra work to make is thread safe.

Written by

iOS and macOS developer, traveller |||| Team Lead at Optimize IT Systems

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade