Add ability to mark block as a completion block

Originator:davbeck
Number:rdar://21684046 Date Originated:06-Jul-2015 08:35 AM
Status:Open Resolved:
Product:Developer Tools Product Version:Swift 2.0
Classification:Feature (New) Reproducible:Always
 
As apps become more and more multithreaded, completion blocks are replacing return values more and more. However, these completion blocks are extremely freeform. They can be copied, saved, called multiple times, or never called at all. But in MANY cases, it is a programming error to a) not call them or b) call them more than once.

It would be exceedingly helpful if Swift supported this pattern by adding compiler checks to enforce basic completion handler rules. A syntax similar to @autoclosure would work really well. Something like the following:

func getStuff(stuffID: Int64, completion: @completion ([String]) -> ()) {
	if stuffID < 0 {
		completion([]) // omitting completion here shoudl cause a compile time error, because completion is never called
		return // omitting return here should cause a compile time error, because completion could be called twice
	}
	
	dispatch_async(dispatch_get_main_queue(), {
		completion(["A", "B", "C"])
	})
}

getStuff(42) { (stuff) in
	
}


Or even:

func getStuff(stuffID: Int64) -> @autoclosure [String] {
	if stuffID < 0 {
		completion([]) // completion now becomes a keyword replacement of return and automatically calls return
	}
	
	dispatch_async(dispatch_get_main_queue(), {
		completion(["A", "B", "C"])
	})
}

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!