[swift-evolution] Guaranteed closure execution
Gwendal Roué
gwendal.roue at gmail.com
Fri Jan 29 01:38:55 CST 2016
Hello,
I’d like to discuss the opportunity to let functions declare that a closure argument is guaranteed to have been executed when the function has returned.
For example:
func f(@noescape(executed) closure: () -> ()) {
closure()
}
The expected advantage is that the compiler would know that a variable set inside the closure is guaranteed to be initialized, and that it can be used after the execution of the function, as below:
let x: Int // Not initialized
f { x = 1 }
print(x) // Guaranteed to be initialized
Today developers have to write pessimistic code like below:
var x: Int = 0 // `var` declaration, with some irrelevant value
f { x = 1 }
print(x)
As for a real world usage, I’d like to access a database in a safe (queued) way, and fetch values out of it:
let items: [Item]
let users: [User]
dbQueue.inDatabase { db in
items = Item.all().fetchAll(db)
users = Item.all().fetchAll(db)
}
Gwendal Roué
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160129/2a72efe8/attachment.html>
More information about the swift-evolution
mailing list