Swift TIL 9
Posted on 2020-06-30 21:02 +0100 in TIL • 2 min read
Some may be happy to know that the frequency of these little notes to myself may reduce real soon, as I'm sort of caught up with my notes, mostly, and I'm unlikely to pick up the book that I'm reading for a couple or so days now
I'm used to the idea of structures and classes from other languages, going way back, but as I first started reading about Swift it wasn't obvious to me why it had them both too. At first glance they appeared to be very similar. It was only as I got a little further into reading that I found out one huge difference (there are others, that pretty much stem from this one): objects created from classes are reference types (which you'd expect, of course), structures on the other hand are value types.
A quick illustration of the difference, in my head anyway, can be found if I go back to using an observer. Take this daft bit of illustrative code for example:
class Person {
var name : String = "No name"
}
var dave = Person() {
didSet {
print( "dave was set" )
}
}
dave.name = "Dave"
If I run that, I get no output. That makes sense. The variable dave
is
initialised to an instance of a Person
but is never subsequently set to
anything else. The following assignment is to a property of the object.
We're working on a reference to an existing object.
But simply change Person
to being a struct
:
struct Person {
var name : String = "No name"
}
var dave = Person() {
didSet {
print( "dave was set" )
}
}
dave.name = "Dave"
and the output looks like this:
$ swift run
[3/3] Linking ref-vs-val
dave was set
That's because the assignment to dave.name
means a new value is created.
This, of course, is just the tip of the iceberg; there are all sorts of
other things to keep in mind that follow on from this, generally relating to
mutability (or the lack thereof). I also imagine this means that, when
there's no obvious benefit either way, the choice of using class
vs
struct
is something that could have performance implications. That's
something for me to look into more another day; but this is a note here to
myself that it's a thing to keep in mind.