Swift的新手,我想知道是否需要像我在Objective-C中一样处理(可能)此代码中的相同问题:

var itemB = EditableItem(title: "Item J")
itemB.onReturn = {(value) in
  var s = itemB.title
  println(value)
}

闭包引用了itemB,而itemB引用了闭包。这是否会导致循环引用并因此导致Swift中的内存泄漏,或者Swift足够聪明,以至于使itemB成为闭包内部的弱变量?

如果没有,我该如何解决?

最佳答案

不,闭包内部的itemB仅在itemB设置在外部时才存在。

例如,您可以在操场上进行测试。

假设我们在您的示例中有这个Class映射:

Import Foundation
class EditableItem {
  var title = ""
  var onReturn: ((String)->Void)?

  init(title: String) {
    self.title = title
  }

  deinit {
    println("Deinit")
  }
}

现在,我们运行类似于您的代码:
// Using optional so that I can set it do nil = will dealloc
var itemB:EditableItem? = EditableItem(title: "Item J")
itemB!.onReturn = {(value) in
  var s = itemB!.title
  println(value)
}

// Execute to make sure anything would retain
itemB!.onReturn!("data")
// var is set to nil, same variable inside the closure
itemB = nil // Deinit will run

保留变量的相同示例:
var retainer:EditableItem? = nil

var itemB:EditableItem? = EditableItem(title: "Item J")
itemB!.onReturn = {(value) in
  retainer = itemB!
  println(value)
}

// If onReturn() would not be executed, itemB would not be retained
itemB!.onReturn!("data")
// deinit will not be called
itemB = nil

和使引用弱的示例:
var retainer:EditableItem? = nil

var itemB:EditableItem? = EditableItem(title: "Item J")
// Make sure retainer is weak
itemB!.onReturn = { [weak retainer](value) in
  retainer = itemB!
  println(value)
  // retainer is set here..
}
// retainer is nil here..
itemB!.onReturn!("data")
// retainer is nil here as well..
itemB = nil // And this will deinit

10-06 15:44