kdgwill
kdgwill

Reputation: 2199

Swift: Pointers to Struct vs Classes

I understand that generally structs in swift are pass-by-value. I use a struct for encapsulating a few bits of information add the struct to a set and later change small bits of its values. However; I seemed to have fallen into an issue whereby the structs are not updating correctly even though I have sprinkled the keyword inout everywhere the parameter requires a struct. My gut instinct was to allocate memory for the struct and refer to it in the set by it's pointer. Would it make sense to simply use a class even though all I need is a list of values that can change.

Upvotes: 0

Views: 732

Answers (2)

Grimxn
Grimxn

Reputation: 22487

Without your code, I can't see what you're doing wrong, but it works for me - Playground minimal example:

struct Grimxn {
    var first: Int
    var second: Int
}

func modify(inout v: Grimxn) {
    v.first++
    v.second--
}

var a = Grimxn(first: 1, second: 2)
print("\(a)") // "Grimxn(first: 1, second: 2)\n"
modify(&a)
print("\(a)") // "Grimxn(first: 2, second: 1)\n" - as required?

I certainly wouldn't want to use pointers - why do that in Swift - use C!

Upvotes: 0

Mr Beardsley
Mr Beardsley

Reputation: 3863

If you need reference semantics, then absolutely use a class. If you want to be able to modify your object both in a data structure as well as other places, a class is what you need. It is perfectly reasonable to use a class just to get reference semantics.

Also so you know, inout on a function parameter does not actually mean pass by reference. What is actually happening is a copy of your struct is made by the function. This copy is then modified in the function and later copied back to the original variable.

Upvotes: 1

Related Questions