问题
I have a function with a completion handler, returning one parameter or more.
In a client, when executing a completion handler, I'd like to have an unowned
reference to self
, as well as having access to the parameter passed.
Here is the Playground example illustrating the issue and the goal I'm trying to achieve.
import UIKit
struct Struct {
func function(completion: (String) -> ()) {
completion("Boom!")
}
func noArgumentsFunction(completion: () -> Void) {
completion()
}
}
class Class2 {
func execute() {
Struct().noArgumentsFunction { [unowned self] in
//...
}
Struct().function { (string) in // Need [unowned self] here
//...
}
}
}
回答1:
As I said in my comment
Struct().function { [unowned self] (string) in
//your code here
}
Capture list and closure parameters that should be the order in closures more info from Apple Documentation
Defining a Capture List
Each item in a capture list is a pairing of the weak or unowned keyword with a reference to a class instance (such as self) or a variable initialized with some value (such as delegate = self.delegate!). These pairings are written within a pair of square braces, separated by commas.
Place the capture list before a closure’s parameter list and return type if they are provided:
lazy var someClosure: (Int, String) -> String = {
[unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in
// closure body goes here
}
If a closure does not specify a parameter list or return type because they can be inferred from context, place the capture list at the very start of the closure, followed by the in keyword:
lazy var someClosure: () -> String = {
[unowned self, weak delegate = self.delegate!] in
// closure body goes here
}
回答2:
Is it just the syntax for including [unowned self] in the closure parameter list you need?
struct Struct {
func function(completion:(String)->()) {
completion("Boom!")
}
}
class Class {
func execute() {
Struct().function { [unowned self] string in
print(string)
print(self)
}
}
}
Class().execute()
来源:https://stackoverflow.com/questions/49302197/add-unowned-self-to-the-closure-argument-swift