Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

Playing around with Swift, coming from a Java background, why would you want to choose a Struct instead of a Class? Seems like they are the same thing, with a Struct offering less functionality. Why choose it then?

share|improve this question
1  
Structures are always copied when they are passed around in your code, and do not use reference counting. source: developer.apple.com/library/prerelease/ios/documentation/swift/… – holex Jun 15 '14 at 18:36
    
I would say that structs are more appropriated to hold data, not logic. To speak in Java terms, imagine structs as "Value Objects". – Vincent Guerci Jun 15 '14 at 19:10
1  
I'm amazed in this whole conversation there is no direct mention of copy-on-write a.k.a. lazy copy. Any concerns about struct copy performance are mostly moot on account of this design. – David James Nov 24 '15 at 14:13
up vote 136 down vote accepted

According to the very popular WWDC 2015 talk Protocol Oriented Programming in Swift (video, transcript), Swift provides a number of features that make structs better than classes in many circumstances.

Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple reference to the same instance as happens with classes. This is especially important when passing around a variable to many classes and/or in a multithreaded environment. If you can always send a copy of your variable to other places, you never have to worry about that other place changing the value of your variable underneath you.

With Structs there is no need to worry about memory leaks or multiple threads racing to access/modify a single instance of a variable.

Classes can also become bloated because a class can only inherit from a single superclass. That encourages us to created huge superclasses that encompass many different abilities that are only loosely related. Using protocols, especially with protocol extensions where you can provide implementations to protocols, allows you to eliminate the need for classes to achieve this sort of behavior.

The talk lays out these scenarios where classes are preferred:

  • Copying or comparing instances doesn't make sense (e.g., Window)
  • Instance lifetime is tide to external effects (e.g., TemporaryFile)
  • Instances are just "sinks"--write-only conduits to external state (e.g.CGContext)

It implies that structs should be the default and classes should be a fallback.

On the other hand, The Swift Programming Language documentation is somewhat contradictory:

Structure instances are always passed by value, and class instances are always passed by reference. This means that they are suited to different kinds of tasks. As you consider the data constructs and functionality that you need for a project, decide whether each data construct should be defined as a class or as a structure.

As a general guideline, consider creating a structure when one or more of these conditions apply:

  • The structure’s primary purpose is to encapsulate a few relatively simple data values.
  • It is reasonable to expect that the encapsulated values will be copied rather than referenced when you assign or pass around an instance of that structure.
  • Any properties stored by the structure are themselves value types, which would also be expected to be copied rather than referenced.
  • The structure does not need to inherit properties or behavior from another existing type.

Examples of good candidates for structures include:

  • The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.
  • A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int.
  • A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.

In all other cases, define a class, and create instances of that class to be managed and passed by reference. In practice, this means that most custom data constructs should be classes, not structures.

Here it is claiming that we should default to using classes and use structures only in specific circumstances. Ultimately, you need to understand the real world implication of value types v.s. reference types and then you can make an informed decision about when to use structs or classes. Also keep in mind that these concepts are always evolving and The Swift Programming Language documentation was written before the Protocol Oriented Programming talk was given.

My personal advice, is to always default to using a struct because they greatly reduce complexity and fallback to classes if the Struct becomes very large or requires some feature that structs and protocols cannot provide, most notably the ability to have multiple variables reference the same data.

share|improve this answer
4  
@ElgsQianChen the whole point of this writeup is that struct should be chosen by default and class should only be used when necessary. Structs are much safer and bug free, especially in a multithreaded environment. Yes, you can always use a class in place of a struct, but structs are preferable. – drewag Sep 22 '14 at 8:22
5  
@drewag That seems to be the exact opposite of what it is saying. It was saying that a class should be the default that you use, not a structure In practice, this means that most custom data constructs should be classes, not structures. Can you explain to me how, after reading that, you get that most data sets should be structures and not classes? They gave a specific set of rules when something should be a struct and pretty much said "all other scenarios a class is better." – Matt Oct 3 '14 at 4:42
1  
@Matt, that's true. The way I choose to look at this is that we have specific places a Struct can be used while a Class can be used anywhere including in place of structs. That means to me that classes are a fallback for when structs will not cut it. – drewag Oct 3 '14 at 4:49
11  
Last line should say, "My personal advice is the opposite of the documentation:"... and then it's a great answer! – Dan Rosenstark Jan 16 '15 at 21:47
2  
Swift 2.2 book still says use classes in most situations. – David James Dec 4 '15 at 19:53

One big advantage is performance. Since struct instances are allocated on stack, and class instances are allocated on heap, structs can be drastically faster.

Consider the following example, which demonstrates 2 strategies of wrapping Int data type (e.g. as part of a mathematics library)

class IntClass {
    var value: Int
    init(_ val: Int) { self.value = val }
}

struct IntStruct {
    var value: Int
    init(_ val: Int) { self.value = val }
}

func + (x: IntClass, y: IntClass) -> IntClass {
    return IntClass(x.value + y.value)
}

func + (x: IntStruct, y: IntStruct) -> IntStruct {
    return IntStruct(x.value + y.value)
}

and measure the performance using

// Test 1: IntClass
var x = IntClass(0)
for i in 1...10000000 {
    x = x + IntClass(1)
}

// Test 2: IntStruct
var y = IntStruct(0)
for i in 1...10000000 {
    y = y + IntStruct(1)
}

UPDATE (1 June 2014):

As of Swift 1.2, XCode 6.3.2, running Release build on iPhone 5S, iOS 8.3, averaged over 5 runs

  • The class version took 9.788332333s
  • The struct version took 0.010532942s

That's 900 times faster.

OLD RESULTS

In release build (on my Macbook), the first test takes 1.10082 sec, while the second one takes 0.02324 sec. That's 50 times faster! (results are roughly the same in debug build).

share|improve this answer
13  
True, but it seems that copying a bunch of structs around would be slower than copying a reference to a single object. In other words it's faster to copy a single pointer around than to copy an arbitrarily large block of memory. – Tylerc230 Feb 26 '15 at 7:00
2  
In most cases you are not just copying a reference, but object's reference counter should be incremented/decremented as well and it can affect performance. – interrupt Jun 1 '15 at 16:38
6  
-1 This test is not a good example because there is only a single var on the struct. Note that if you add several values and an object or two, the struct version gets comparable to the class version. The more vars you add, the slower the struct version gets. – joshrl Jun 2 '15 at 14:07
2  
@joshrl got your point, but an example is "good" or not depends on specific situation. This code was extracted from my own app, so it is a valid use case, and using structs did massively improves performance for my app. It's just probably not a common use case (well, the common use case is, for most apps, no one cares about how fast data can be passed around, since the bottleneck happens somewhere else, e.g. network connections, anyway, optimization is not that critical when you have GHz devices with GBs or RAM). – Khanh Nguyen Jun 3 '15 at 1:59
    
@KhanhNguyen thanks for the benchmark and +1 as a compensation. This is a decisive example for some use cases e.g. rendering lots of objects (again is some context). – Shaikh Sonny Aman Aug 10 '15 at 13:50

Similarities between structs and classes.

I created gist for this with simple examples. https://github.com/objc-swift/swift-classes-vs-structures

And differences

1. Inheritance.

structures can't inherit in swift. If you want

class Vehicle{
}

class Car : Vehicle{
}

Go for an class.

2. Pass By

Swift structures pass by value and class instances pass by reference.

Contextual Differences

Struct constant and variables

Example (Used at WWDC 2014)

struct Point{

   var x = 0.0;
   var y = 0.0;

} 

Defines a struct called Point.

var point = Point(x:0.0,y:2.0)

Now if I try to change the x. Its a valid expression.

point.x = 5

But if I defined a point as constant.

let point = Point(x:0.0,y:2.0)
point.x = 5 //This will give compile time error.

In this case entire point is immutable constant.

If I used a class Point instead this is a valid expression. Because in a class immutable constant is the reference to the class itself not its instance variables (Unless those variables defined as constants)

share|improve this answer
    
You can inherit structs in Swift gist.github.com/AliSoftware/9e4946c8b6038572d678 – iosfanboy9 Sep 13 '15 at 16:25
5  
The above gist is about how we can achieve inheritance flavors for struct. You will see syntax like. A: B. It is struct called A implements protocol called B. Apple documentation clearly mention that struct doesn't support pure inheritance and it doesn't. – MadNik Sep 16 '15 at 12:43

Here are some other reasons to consider:

  1. structs get an automatic initializer that you don't have to maintain in code at all.

    struct MorphProperty {
       var type : MorphPropertyValueType
       var key : String
       var value : AnyObject
    
       enum MorphPropertyValueType {
           case String, Int, Double
       }
     }
    
     var m = MorphProperty(type: .Int, key: "what", value: "blah")
    

To get this in a class, you would have to add the initializer, and maintain the intializer...

  1. Basic collection types like Array are structs. The more you use them in your own code, the more you will get used to passing by value as opposed to reference. For instance:

    func removeLast(var array:[String]) {
       array.removeLast()
       println(array) // [one, two]
    }
    
    var someArray = ["one", "two", "three"]
    removeLast(someArray)
    println(someArray) // [one, two, three]
    
  2. Apparently immutability vs. mutability is a huge topic, but a lot of smart folks think immutability -- structs in this case -- is preferable. Mutable vs immutable objects

share|improve this answer
1  
It's true you get automatic initialisers. You also get an empty initialiser when all the properties are Optional. But, if you have a struct in a Framework you need to actually write the initialiser yourself if you want it to be available outside internal scope. – Abizern Mar 11 at 13:46
    
@Abizern didn't know that, thanks! – Dan Rosenstark Mar 11 at 13:58
2  
@Abizern confirmed -- stackoverflow.com/a/26224873/8047 -- and man that is annoying. – Dan Rosenstark Mar 11 at 22:26
    
I remember reading that there are good reasons for it, so it's expected behaviour. Can't remember why, exactly. – Abizern Mar 11 at 22:29
1  
@Abizern there are great reasons for everything in Swift, but every time something is true in one place and not in another, the developer has to know more stuff. I guess here's where I'm supposed to say, "it's exciting to work in such a challenging language!" – Dan Rosenstark Mar 12 at 1:13

Some advantages:

  • automatically threadsafe due to not being shareable
  • uses less memory due to no isa and refcount (and in fact is stack allocated generally)
  • methods are always statically dispatched, so can be inlined (though @final can do this for classes)
  • easier to reason about (no need to "defensively copy" as is typical with NSArray, NSString, etc...) for the same reason as thread safety
share|improve this answer
    
Not sure if it's outside the scope of this answer, but can you explain (or link, I guess) the "methods are always statically dispatched" point? – Dan Rosenstark Mar 12 at 1:14
    
Sure. I can also attach a caveat to it. The purpose of dynamic dispatch is to pick an implementation when you don't know up front which one to use. In Swift, that can either be due to inheritance (might be overridden in a subclass), or due to the function being generic (you don't know what the generic parameter will be). Structs can't be inherited from and whole-module-optimization + generic specialization mostly eliminates the unknown generics, so methods can just be called directly rather than having to look up what to call. Unspecialized generics still do dynamic dispatch for structs though – Catfish_Man Mar 12 at 6:37
    
Thanks, great explanation. So we're expecting more runtime speed, or less ambiguity from an IDE perspective, or both? – Dan Rosenstark Mar 15 at 20:48
1  
Mostly the former. – Catfish_Man Mar 15 at 23:10

With classes you get inheritance and are passed by reference, structs do not have inheritance and are passed by value.

There are great WWDC sessions on Swift, this specific question is answered in close detail in one of them. Make sure you watch those, as it will get you up to speed much more quickly then the Language guide or the iBook.

share|improve this answer
    
Could you provide some links from what you mentioned? Cause on WWDC there are quite a few to choose from, I'd like to watch the one talking about this specific topic – marczking Feb 4 '15 at 14:59
    
For me this is a good start here: github.com/raywenderlich/… – marczking Feb 4 '15 at 15:58
1  
He's probably talking about this great session: Protocol-Oriented Programming in Swift. (Links: video, transcript) – zekel Feb 3 at 18:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.