以不同方式创建数组时,反初始化顺序不同

Deinitialization order is different when creating array differently

TL;DR: 为什么,创建数组时连同初始值一起去初始化,直接去初始化,但是创建完数组后填充数组值产生不同的行为?


我在JavaScript之后学习Swift,它有GC,所以ARC和反初始化的概念对我来说有点新手。为了更深入地理解它,我根据 example from the official documentation:

编写了以下代码
// definitions; see the next two snippets for usage
class Bank {
    static var coins: Int = 100 {
        didSet {
            let diff = coins - oldValue
            let sign = diff < 0 ? "-" : "+"

            print("Bank: \(oldValue) \(sign) \(diff.magnitude) = \(coins)")
        }
    }

    static func give(_ amount: Int, to user: User) {
        guard amount <= coins else {
            print("[ERROR] The bank does not have enough coins; requested \(amount - coins) more coins than available")
            return
        }

        user.purse += amount
        coins -= amount
    }

    static func take(_ amount: Int, from user: User) {
        user.purse -= amount
        coins += amount
    }
}

class User {
    private static var count = 0

    let id: Int

    var purse = 0

    init() {
        User.count += 1

        id = User.count
    }

    deinit {
        print("User #\(id) perished")

        Bank.take(purse, from: self)
    }
}

当我使用现有用户实例 (array = [value, value]) 创建数组时,取消初始化发生在分配给 nil (array[0] = nil):

之后
var users: [User?] = [
    User(),
    User(),
]

Bank.give(90, to: users[0]!)
users[0] = nil
Bank.give(50, to: users[1]!) // works

//  Bank: 100 - 90 = 10
//  User #1 perished
//  Bank: 10 + 90 = 100
//  Bank: 100 - 50 = 50

… 但是当我首先创建一个空数组然后用值填充它时 (array = []; array[0] = value; array[1] = value),取消初始化会在稍后的某个随机点发生:

var users = [User?](repeating: nil, count: 2)

users[0] = User()
users[1] = User()

Bank.give(90, to: users[0]!)
users[0] = nil
Bank.give(50, to: users[1]!) // fails

//  Bank: 100 - 90 = 10
//  [ERROR] The bank does not have enough coins; requested 40 more coins than available
//  User #1 perished
//  Bank: 10 + 90 = 100

从编译器的角度来看有什么区别?造成这种差异的原因是什么?

TL;DR 不要依赖 deallocation/de-initialization 时机。

确切地弄清楚何时释放,因此 de-initialization 发生在之前,发生是一个 non-trivial 过程。

线程(几乎每个应用程序都是 multi-threaded,即使它不直接使用线程)、临时编译器、传递值等都有助于准确混淆最后一次引用对象的时间消失。

除此之外,Swift 游乐场本身可能会保留 non-obvious 对象的引用,因为它的工作方式,这似乎是这里发生的事情。将您的代码放入 Swift 命令行应用程序对我们有用,但是 YMMV!

HTH