Swift 在闭包中使用函数参数

Swift using function parameter inside closure

我只是想在 swift 闭包中使用函数参数而不会有内存泄漏,所以我只是想确认如果我按照以下方式进行操作,是否会出现任何与内存相关的问题?请告诉我

func someMethod(someValue: String) {
    weak var weakSelf = self
    var copyOfSomeValue: String? = someValue.copy() as? String
    self.someOtherMethodWithCompletion(completionHandler: { () -> Void in
        if let strongSelf = weakSelf, let originalValue = copyOfSomeValue {
            strongSelf.updateMyViewWithText(originalValue)
        }
    })
}

如果使用 swift,您应该使用 [unowned self] 并正常使用 swift,例如:

func someMethod(someValue: String) {
    var copyOfSomeValue: String? = someValue.copy() as? String
    self.someOtherMethodWithCompletion(completionHandler: { () ->
        [unowned self]
         in
        if let originalValue = copyOfSomeValue {
            self.updateMyViewWithText(originalValue)
        }
    })
}

你应该只对可能导致引用循环的变量使用weak或unowned。它们之间的区别是:

Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization

Stringvalue type. Even though closures capture 它们的引用,除非您要在捕获后更改 someValue,否则无需复制。即便如此,您最好还是使用捕获列表 [someValue],当您需要声明 [weak self].

时也会使用它们

使用 weakunowned 是视情况而定,阅读它们 here

func someMethod(someValue: String) {
    someOtherMethodWithCompletion { [weak self] in
        self?.updateMyViewWithText(someValue)
    }
}