[swift-evolution] [Draft] Guarded closures and `@guarded` arguments

Florent Bruneau florent.bruneau at intersec.com
Mon Feb 20 08:33:41 CST 2017



> Le 20 févr. 2017 à 06:35, Brent Royal-Gordon via swift-evolution <swift-evolution at swift.org> a écrit :
> 
>> On Feb 19, 2017, at 2:57 PM, Matthew Johnson via swift-evolution <swift-evolution at swift.org> wrote:
>> 
>> A guarded closure may be created by prefixing a bound instance method reference with the `?` sigil:
>> 
>> ```swift
>> let guarded = ?myObject.myMethod
>> 
>> // desugars to:
>> let guarded = { [weak myObject] in
>> guard let myObejct = myObject else {
>>   return
>> }
>> myObject.myMethod()
>> }
>> ```
> 
> I like this in principle, but I don't like the syntax. The `?` is cryptic and looks pretty strange in prefix position. I think what I'd like to see is:
> 
> 	let guarded = weak myObject.myMethod

I like the idea of weak closures even if this may conflict with the fact closures are already internally refcounted object. While we cannot have weak references to closure in the language, using `weak` might be misleading in some ways.

In term of syntax, the `weak` keyword looks nice (much better than the '?' and @guarded once). The weak could be used on both sides.

```swift
addAction(action: weak Action)
addAction(action: weak myAction)
```

However, I think this might still look weird with inlined closures, in particular in case you use the suffix syntax for closures:

```swift
addAction() weak {
    /* */
}
```


More information about the swift-evolution mailing list