如何在Swift中存储对整数的引用 [英] How to store a reference to an integer in Swift
本文介绍了如何在Swift中存储对整数的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道swift同时具有引用类型和值类型.而且我知道Int是一种值类型.但是如何存储对整数的引用?
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
我尝试使用盒装类型,并且尝试使用Int数组,但都不能用于保存对整数的引用.
I tried using boxed types, and I tried using array of Int, but neither works for holding a reference to integer.
我想我可以写自己的
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)
似乎有点尴尬.
推荐答案
不幸的是,在Swift中没有引用类型Integer
或类似的东西,因此您必须自己创建Box-Type.
Unfortunately there is no reference type Integer
or something like that in Swift so you have to make a Box-Type yourself.
例如通用的一个:
class Reference<T> {
var value: T
init(_ value: T) { self.value = value }
}
这篇关于如何在Swift中存储对整数的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文