快速返回参考文献

时间:2018-08-21 20:08:57

标签: swift

采用以下示例:

struct Foo {
    var bar: Int = 0
}

func getBar (forFoo foo: Foo) -> Int {
    return foo.bar
}

let foo = Foo()
var bar = getBar(forFoo: foo)
bar = 1
print("foo.bar: \(foo.bar)")

getBar中,我希望能够返回对foo.bar reference ,以便当我修改bar时它会更改 foo.bar的值不只是bar

我该怎么做?

1 个答案:

答案 0 :(得分:0)

稍微玩弄一下之后,看来NSNumber并没有真正完成您想要的操作,因此您需要编写自己的自定义包装。例如:

struct Foo {
    let bar = IntWrapper(0)
}

class IntWrapper {
    var value: Int
    init (_ value: Int) {
        self.value = value
    }
}    

func getBar (forFoo foo: Foo) -> IntWrapper {
    return foo.bar
}

let foo = Foo()
let bar = getBar(forFoo: foo)
bar.value = 1
print("foo.bar: \(foo.bar.value)") // prints 1

请注意,我将某些var更改为let,因为如果您要更改引用本身,则只需在引用类型上使用var