Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
import UIKit
// closures -> function without name
// parameter return type
let myClosure : (_ x:Int,_ y:Int) -> Int = {
(x,y) in return x*y
}
print(myClosure(10,10))
let clousure:(_ n:Int,_ n1:Int) -> Int = {
$0 * $1 // we not need to use return swift
}
// clousers may be optional
let myClosure1 : ((_ x:Int,_ y:Int) -> Int)? = {
$0*$1
}
if let closure = myClosure1{
print(closure(10,100))
}
myClosure1?(10,10) // if not nil the (10,10) execute
// closure can use as aparameter in function
func makeRequest(authenticated: @autoclosure ()->Bool){ // @autoclousure make { } by default
if authenticated(){
print("request suceesfully")
}else {
print("please sign in first")
}
}
makeRequest(authenticated: true ) // or{true} but @autoclosure make {}
makeRequest(authenticated: false)
func make_request(name:String , authenticate1:()->Bool){
if authenticate1(){
print("Requesting --- ")
}else{
print("please sign in first")
}
}
make_request(name: "mahmoud" ){true} // if the closure the last parameter in function
// we can use this synax while calling function
makeRequest(authenticated: true)
Advertisements
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.
AcceptLearn more