Different types of Closures in Swift

import UIKit

let emptyclosure = {
	print("empty closure")
}

emptyclosure()

let closureWithStringAsInputArgument = { (name: String) -> Void in
	print(name)
}

closureWithStringAsInputArgument("closureWithStringAsInputArgument")

let closureWithStringAsInputArgumentAndReturnArgument = {
	(name: String) -> String in
	return "\(name) name"
}

print(closureWithStringAsInputArgumentAndReturnArgument("tom is the "))

func closureWithNoEscaping(onCompletion: (Bool)->()) -> Void {
	print("inside testClosure")
	onCompletion(false)
}

closureWithNoEscaping { (isFinished) in
	if(isFinished) {
		print("finished")
	} else {
		print("not finished")
	}
}

func closureWithEscaping(onCompletion: @escaping (Bool) -> ()) {
	DispatchQueue.main.async {
		sleep(5)
		onCompletion(true)
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *