[swift-evolution] @noescape loop hole

Fabian Ehrentraud Fabian.Ehrentraud at willhaben.at
Fri Aug 26 01:58:28 CDT 2016


The implemented change for closures being @noescape by default is awesome, but an important case was missed. When the closure is stored into a local variable, there currently is no way to make that variable non-escaping.


class A {
	
	let n: Int = 1
	var cp: (() -> Int)?
	
	func f1() {
		// when directly constructing a new closure in the function call, the compiler knows it will be non-escaping, and no explicit `self` is needed in the closure...
		f2(c: { n })
		
		// ... but when storing the closure in an intermediate variable, it is not assumed as non-escaping, and explicit `self` is needed, and also we cannot prevent that it can be stored in some escaping way
		let c: () -> Int = {
			// the closure variable would need to know if it is escaping or not, as this has impact on whether the user needs to think about problems with strong capture semantics
			return self.n
		}
		f2(c: c)
		
		// this should actually not be allowed, unless the closure c is marked as @escaping
		cp = c
	}
	
	func f2(c: () -> Int) -> Int {
		return c()
	}
	
}


Is this rather a bug in the implementation of SE-0103, or a new feature request?


best,
Fabian


More information about the swift-evolution mailing list