How to store a reference to an integer in Swift

2020-03-05 03:11发布

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.

2条回答
Viruses.
2楼-- · 2020-03-05 03:29

You can also use closures. I think these better because they are more powerful and also more specific. They not only store a reference, but they also indicate how the reference will be used. For example,

var x:Int = 1
var setx = { (a:Int) in x = a }
var getx = { x }
setx(getx() + 1)
println(x)             // This will print 2

I don't recommend actually defining getx/setx. Define a closure that does a specific task for your application.

查看更多
家丑人穷心不美
3楼-- · 2020-03-05 03:39

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 }
}
查看更多
登录 后发表回答