MysteryPancake MysteryPancake - 6 days ago 7
Swift Question

Swift: Updating struct variables?

I’m fairly new to Swift, and I’ve stumbled across this problem today which will help me a LOT if there’s an answer for. The code below explains it:

struct Foo {
var x: Float
mutating func change() {
x += 1
}
}

struct Bar {
var y: Float
}

var foo = Foo(x: 1)
let bar = Bar(y: foo.x)

foo.change()

print(foo.x) // 2.0
print(bar.y) // 1.0 (how can I make this 2.0 as well?)


I thought I might have to use pointers but I have no idea how to, and I have no clue if that’d even work.
Any ideas will help!

Answer

One way to get what you want here is to define Bar to keep a reference to Foo. And since you want a change to an instance of Foo to carry over to the reference held by a Bar, you would need to make Foo a class instead of a struct.

Here's one possible solution:

class Foo {
    var x: Float

    init(x: Float) {
        self.x = x
    }

    func change() {
        x += 1
    }
}

struct Bar {
    var foo : Foo
    var y : Float { return foo.x }

    init(foo: Foo) {
        self.foo = foo
    }
}

var foo = Foo(x: 1)
let bar = Bar(foo: foo)

foo.change()

print(foo.x) // 2.0
print(bar.y) // 2.0 as asked
Comments