Reference to Property in Closure Requires Explicit 'Self.' to Make Capture Semantics Explicit

Reference to property in closure requires explicit 'self.' to make capture semantics explicit

Before answering this question you must know what a memory cycle is. See Resolving Strong Reference Cycles Between Class Instances From Apple's documenation


Now that you know what a Memory cycle is:

That error is Swift compiler telling you

"Hey the NSURLSession closure is trying to keep webviewHTML in
the heap and therefor self ==> creating a memory cycle and I don't
think Mr.Clark wants that here. Imagine if we make a request which takes
forever and then the user navigates away from this page. It won't
leave the heap.I'm only telling you this, yet you Mr.Clark must create a weak reference to the self and use that in the closure."

We create (ie capture) the weak reference using [weak self]. I highly recommend you see the attached link on what capturing means.

For more information see this moment of Stanford course.

Correct Code

func post(url: String, params: String) {

let url = NSURL(string: url)
let params = String(params);
let request = NSMutableURLRequest(URL: url!);
request.HTTPMethod = "POST"
request.HTTPBody = params.dataUsingEncoding(NSUTF8StringEncoding)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
[weak weakSelf self] data, response, error in

if error != nil {
print("error=\(error)")
return
}

var responseString : NSString!;
responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

weakSelf?.webviewHTML.loadHTMLString(String(responseString), baseURL: nil)
// USED `weakSelf?` INSTEAD OF `self`
}
task.resume();
}

For in depth details, see this Shall we always use [unowned self] inside closure in Swift

Call to method in closure requires explicit self

Add self and make sure you hop back on the main thread before you display any alert message to the user.

DispatchQueue.main.async() {
self.displayAlertMessage(userMessage: "Your credentials are incorrect. Please check your email and password.")
}

Why is declaring self not required in structures where it's required in classes?

The purpose of including self when using properties inside an escaping closure (whether optional closure or one explicitly marked as @escaping) with reference types is to make the capture semantics explicit. As the compiler warns us if we remove self reference:

Reference to property 'someProperty' in closure requires explicit use of 'self' to make capture semantics explicit.

But there are no ambiguous capture semantics with structs. You are always dealing with a copy inside the escaping closure. It is only ambiguous with reference types, where you need self to make clear where the strong reference cycle might be introduced, which instance you are referencing, etc.


By the way, with class types, referencing self in conjunction with the property is not the only way to make the capture semantics explicit. For example, you can make your intent explicit with a “capture list”, either:

  • Capture the property only:

     class SomeClass {
    var someProperty = 1

    func someMethod(completion: @escaping () -> Void) { ... }

    func anotherMethod() {
    someMethod { [someProperty] in // this captures the property, but not `self`
    print(someProperty)
    }
    }
    }
  • Or capture self:

     class SomeClass {
    var someProperty = 1

    func someMethod(completion: @escaping () -> Void) { ... }

    func anotherMethod() {
    someMethod { [self] in // this explicitly captures `self`
    print(someProperty)
    }
    }
    }

Both of these approaches also make it explicit what you are capturing.

Implicit self in @escaping Closures when Reference Cycles are Unlikely to Occur Swift 5.3

You still need to manually specify weak and unowned captures of self. The only change SE-0269 results in is that you don't need to explicitly write out self. when accessing instance properties/methods when acknowledging that you capture self strongly by using [self].

In case of [weak self] you still need to explicitly write self. in the closure, but when using [unowned self], you can omit self. just as when using [self].

execute { [weak self] in
x += 1 // Error: Reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit
}

execute { [weak self] in
self?.x += 1 // need to manually specify `self?.`
}

execute { [unowned self] in
x += 1 // compiles fine
}

Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit in Swift

As others said, do what it says.
Instead of:

present(vc, animated: true, completion: nil)

adding self gets:

self.present(vc, animated: true, completion: nil)

Why do closures require an explicit `self` when they're all non-escaping by default in Swift 3?

In Swift 3, all closures are non-escaping by default

No, in Swift 3, only closure function arguments (i.e function inputs that are functions themselves) are non-escaping by default (as per SE-0103). For example:

class A {

let n = 5
var bar : () -> Void = {}

func foo(_ closure: () -> Void) {
bar = closure // As closure is non-escaping, it is illegal to store it.
}

func baz() {
foo {
// no explict 'self.' required in order to capture n,
// as foo's closure argument is non-escaping,
// therefore n is guaranteed to only be captured for the lifetime of foo(_:)
print(n)
}
}
}

As closure in the above example is non-escaping, it is prohibited from being stored or captured, thus limiting its lifetime to the lifetime of the function foo(_:). This therefore means that any values it captures are guaranteed to not remain captured after the function exits – meaning that you don’t need to worry about problems that can occur with capturing, such as retain cycles.

However, a closure stored property (such as bar in the above example) is by definition escaping (it would be nonsensical to mark it with @noescape) as its lifetime not limited to a given function – it (and therefore all its captured variables) will remain in memory as long as the given instance remains in memory. This can therefore easily lead to problems such as retain cycles, which is why you need to use an explicit self. in order to make the capturing semantics explicit.

In fact, case in point, your example code will create a retain cycle upon viewDidLoad() being called, as someClosure strongly captures self, and self strongly references someClosure, as it's a stored property.

It's worth noting that as an extension of the "stored function properties are always escaping" rule, functions stored in aggregates (i.e structures and enumerations with associated values) are also always escaping, as there's no restrictions on what you do with such aggregates. As pointed out by pandaren codemaster, this currently includes Optional – meaning that Optional<() -> Void> (aka. (() -> Void)?) is always escaping. The compiler might eventually make this a special case for function parameters though, given that optional is already built on a lot of compiler magic.


Of course, one place where you would expect to be able to use the @noescape attribute is on a closure that’s a local variable in a function. Such a closure would have a predictable lifetime, as long as it isn’t stored outside of the function, or captured. For example:

class A {

let n = 5

func foo() {

let f : @noescape () -> Void = {
print(n)
}

f()
}
}

Unfortunately, as @noescape is being removed in Swift 3, this won't be possible (What's interesting is that in Xcode 8 GM, it is possible, but yields a deprecation warning). As Jon Shier says, we’ll have to wait for it to be re-added to the language, which may or may not happen.



Related Topics



Leave a reply



Submit