Last active
June 25, 2018 00:37
-
-
Save novinfard/807504260a9ff9ddd1b7c01248cbe6d3 to your computer and use it in GitHub Desktop.
[Usage of Closures]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let guests = ["Ahmad", "Mohsen", "Ehsan"] | |
// map closure | |
guests.map { | |
print("Hello \($0)") | |
} | |
let messages = guests.map { (name) -> String in | |
return name + "!" | |
} | |
print(messages) | |
// reusable closures | |
let greeting = { | |
(name: String) -> Void in | |
print("Hello guest named \(name)") | |
} | |
let sayGoodbye : (String) -> () = { | |
print("Goodbye \($0)") | |
} | |
guests.map(greeting) | |
guests.map(sayGoodbye) | |
let greeting2 = { | |
(name: String) -> Void in | |
if(name.hasPrefix("A")) { | |
print("Hello guest named \(name)") | |
} else { | |
print("Dear \(name), you are not invited") | |
} | |
} | |
guests.map(greeting2) | |
// preservation of variables inside closures | |
func temperatures(calculate:(Int)->Void) { | |
let numbers = [72,74,76,68,70,72,66] | |
numbers.map(calculate) | |
} | |
func testFunction() { | |
var total = 0 | |
var count = 0 | |
let addTemps = { | |
(num: Int) -> Void in | |
total += num | |
count += 1 | |
} | |
temperatures(calculate: addTemps) | |
print("Total: \(total)") | |
print("Count: \(count)") | |
print("Average: \(total/count)") | |
} | |
testFunction() | |
// usage 2 | |
struct TestType { | |
typealias getNumClosure = ((Int, Int) -> Int) | |
var numOne = 5 | |
var numTwo = 8 | |
var results = 0; | |
mutating func getNum(handler: getNumClosure) -> Int { | |
results = handler(numOne,numTwo) | |
print("Number to Use: \(results)") | |
return results | |
} | |
} | |
var max: TestType.getNumClosure = { | |
if $0 > $1 { | |
return $0 | |
} else { | |
return $1 | |
} | |
} | |
var min: TestType.getNumClosure = { | |
if $0 < $1 { | |
return $0 | |
} else { | |
return $1 | |
} | |
} | |
var multiply: TestType.getNumClosure = { | |
return $0 * $1 | |
} | |
var second: TestType.getNumClosure = { | |
return $1 | |
} | |
var answer: TestType.getNumClosure = { | |
_ = $0 + $1 // to prevent error of not using parameters | |
return 42 | |
} | |
var myClass = TestType() | |
myClass.getNum(handler: max) | |
myClass.getNum(handler: min) | |
myClass.getNum(handler: multiply) | |
myClass.getNum(handler: second) | |
myClass.getNum(handler: answer) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment