iOS Swift Enums and Structs Structs Stored Properties

Ronny Kibet
Ronny Kibet
47,392 Points

Whats the difference between a struct and a class in swift?

What's the difference between struct and class.

2 Answers

Stone Preston
Stone Preston
41,662 Points

the main difference is that structs are value types and classes are reference types.

When you make a copy of a value type, it copies all the data from the thing you are copying into the new variable. They are 2 seperate things and changing one does not affect the other

When you make a copy of a reference type, the new variable refers to the same memory location as the thing you are copying. This means that changing one will change the other since they both refer to the same memory location

Here is an article from apple comparing structs and classes

this post on SO has a nice example. The top answer is below:

<Here's an example with a class. Note how when the name is changed, the instance referenced by both variables is updated. Bob is now Sue, everywhere that Bob was ever referenced.

class SomeClass {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var aClass = SomeClass(name: "Bob")
var bClass = aClass // aClass and bClass now reference the same instance!
bClass.name = "Sue"

println(aClass.name) // "Sue"
println(bClass.name) // "Sue"

And now with a struct we see that the values are copied and each variable keeps it's own set of values. When we set the name to Sue, the Bob struct in aStruct does not get changed.

struct SomeStruct {
    var name: String
    init(name: String) {
        self.name = name
    }
}

var aStruct = SomeStruct(name: "Bob")
var bStruct = aStruct // aStruct and bStruct are two structs with the same value!
bStruct.name = "Sue"

println(aStruct.name) // "Bob"
println(bStruct.name) // "Sue"

So for representing a stateful complex entity, a class is awesome. But for values that are simply a measurement or bits of related data, a struct makes more sense so that you can easily copy them around and calculate with them or modify the values without fear of side effects.

Ronny Kibet
Ronny Kibet
47,392 Points

Thank you Stone. That covers it. :) Well done.

Question. To be clear...In the Class example Stone said that aClass and bClass now reference the same instance at 'var bClass = aClass'. Is the instance 'name'? Also why are var and init both using 'name'?