Search code examples
swiftreference-type

How to store a reference to an integer in Swift


I know swift has both reference types and value types. And I know Int is a value type. But how can I store a reference to an integer?

var x:Int = 1
var y:Int = x   // I want y to reference x (not copy)
++y
println(x)     // prints 1, but I want 2

I tried using boxed types, and I tried using array of Int, but neither works for holding a reference to integer.

I guess I can write my own

class IntRef {
    var a:Int = 0
    init(value:Int) { a = value }
}

var x:IntRef = IntRef(value: 3)
var y = x
++y.a
println(x.a)

seems a bit awkward.


Solution

  • Unfortunately there is no reference type Integer or something like that in Swift so you have to make a Box-Type yourself.

    For example a generic one:

    class Reference<T> {
        var value: T
        init(_ value: T) { self.value = value }
    }