1)
{(parameters) -> ReturnType in
statements
}
2)
{statements}
let c2 = {(str: String) -> String in
return "Hello, \(str)"
}
let c = { print("Hello, swift")}
c()
※ closure를 호출할 떄는 argument label을 호출하지 않는다.
let c2 = {(str: String) -> String in
return "Hello, \(str)"
}
let result = c2("Closure")
print(result)
ex) - 상수로 저장 된 클로져를 argument로 전달하기
let c2 = {(str: String) -> String in
return "Hello, \(str)"
}
//typealias SimpleStringClosure = (String) -> String
func perform(closure: (String)-> String){
print(closure("iOS"))
}
perform(closure: c2)
==> c2("iOS")
Hello, iOS
ex)
let products = [
"MacBook Air", "MacBook Pro",
"iMac", "iMac Pro", "Mac Pro", "Mac mini",
"iPad Pro", "iPad", "iPad mini",
"iPhone Xs", "iPhone Xr", "iPhone 8", "iPhone 7",
"AirPods",
"Apple Watch Series 4", "Apple Watch Nike+"
]
// name 중 "Pro"를 가지고 있는 string을 참,거짓으로 나누고, 참인 것을 가져온다!
var proModels = products.filter({(name:String) -> Bool in
return name.contains("Pro")
})
print(proModels)
var proModels = products.filter({(name: String) -> Bool in
return name.contains("Pro")
})
==
var proModels = products.filter({(name) in
return name.contains("Pro")
})
==
// 첫번째 파라미터가 $0, 두번 째 파라미터가 $1
products.filter({
return $0.contains("Pro")
})
==
products.filter({
$0.contains("Pro")
})
==
products.filter(){
$0.contains("Pro")
}
==
products.filter{
$0.contains("Pro")
}