2

我有三个类 A、B 和 C。A 有一个名为 rA 的资源。我想要实现的是所有这些实例都引用了完全相同的资源。

因此,用 Swift 术语具体来说:

A 类有一个名为 foo 的属性:

private var foo : [Bar] = [Bar]() // shared resource

B 类有一个名为 foo 的属性,它作为 inout 参数传递给初始化程序:

private var foo : [Bar]!
init(inout foo:[Bar]){
    self.foo = foo
}

C类类似于B类

如果我foo从 A 类转到 B 类(或 C),地址怎么会改变?

在 AI 中,它会将其传递给 B(或 C),如下所示:

let b = B(foo: &self.foo)

当我foo在 A 中初始化后打印地址时,它给我的地址与在 B 中分配后的地址不同。

class A{
    private var foo = [Bar]()
    func someFunc(){
        NSLog("\n\n [A] \(unsafeAddressOf(self.foo))\n\n") // different from output in B
        let b = B(foo: &self.foo)

    }
}

class B{
    private var foo: [Bar]!
    init(inout foo: [Bar]){
         self.foo = foo
         NSLog("\n\n [B] \(unsafeAddressOf(self.foo))\n\n")
    }
}

任何想法为什么会这样?

4

1 回答 1

3

Swift arrays are value types, therefore in

self.foo = foo

you assign the value of foo to self.foo. This are two independent arrays now (even if the actual elements are copied only when one of the arrays is mutated).

Also you cannot take the address of a Swift array with unsafeAddressOf() because that function takes an AnyObject parameter which is an instance of a class, i.e. a value type. In

 unsafeAddressOf(self.foo)

the Swift compiler actually bridges the Swift array to an NSArray. As demonstrated in Swift, Strings and Memory Addresses, this may or may not result in the same object when done repeatedly. In any case, the printed address is not the storage location of the Swift array.

If you need a real reference which you can pass around then you can wrap the array in a class. Using NS(Mutable)Array might also be an option, but then you lose many Swift features.

于 2015-12-10T21:47:26.960 回答