例如..我想将一些字典传入其初始化程序中的一个类,我想在我的类中引用这些字典..问题是当我将它们设置为属性时,它们实际上是被复制的,而不是引用。
示例:
var activeDict: [Int: Projectile]
var inactiveDict: [Int: Projectile]
init(inout activeDict: [Int: Projectile], inout inactiveDict: [Int: Projectile]) {
self.activeDict = activeDict
self.inactiveDict = inactiveDict
我希望在班上使用activeDict
和inactiveDict
。我希望它们成为传入原件的参考。
答案 0 :(得分:1)
你可以将UnsafeMutablePointer存储到字典中,这是一个在操场上测试的例子:
var dict = ["hejj": 1]
class A<T> {
var myDictRef: UnsafeMutablePointer<T>
init(ref: UnsafeMutablePointer<T>) {
self.myDictRef = ref
}
}
let a = A(ref: &dict)
a.myDictRef.memory["asd"] = 3
a.myDictRef.memory
dict
<强>更新强>
在你的情况下使用它:
var activeDict: UnsafeMutablePointer<[Int: Projectile]>
var inactiveDict: UnsafeMutablePointer<[Int: Projectile]>
init(activeDict: UnsafeMutablePointer<[Int: Projectile]>, inactiveDict: UnsafeMutablePointer<[Int: Projectile]>) {
self.activeDict = activeDict
self.inactiveDict = inactiveDict
}
每当你想使用activeDict或inactiveDict时,你可以用它们的内存属性调用指针后面的字典,如:
activeDict.memory[YourKey] = YourValue