Skip to content

Instantly share code, notes, and snippets.

@thanhluu
Last active May 19, 2016 16:37
Show Gist options
  • Save thanhluu/2bd2291ee9d61e579a79064a94d4a478 to your computer and use it in GitHub Desktop.
Save thanhluu/2bd2291ee9d61e579a79064a94d4a478 to your computer and use it in GitHub Desktop.
Higher Order Functions
func printString(aString: String) {
print("Printing the string passed in: \(aString)")
}
printString("Hi, my name is Thanh")
let someFunction: String -> Void = printString
someFunction("Hi, look at me!")
/*****************/
func sum(a: Int, b: Int) -> Int {
return a + b
}
let addTwoNumbers = sum
addTwoNumbers(1,b: 2)
/*****************/
func displayString(a: String -> Void) {
a("I'm a function inside a function!")
}
displayString(printString)
/*****************/
extension Int {
func apply(operaton: Int -> Int) -> Int {
return operaton(self)
}
}
func double(value: Int) -> Int {
return value * 2
}
10.apply(double)
func closestMultibleOfSix(value: Int) -> Int {
for x in 1...1000 {
let multiple = x * 6
if multiple - value < 6 && multiple > value {
return multiple
} else if multiple == value {
return value
}
}
return 0
}
32.apply(closestMultibleOfSix)
12.apply(closestMultibleOfSix)
200.apply(closestMultibleOfSix)
/*****************/
typealias IntegerFunction = Int -> ()
func gameCounter() -> IntegerFunction {
var counter = 0
func increment(i: Int) {
counter += i
print("Counter value: \(counter)")
}
return increment
}
let aCounter = gameCounter()
aCounter(1)
aCounter(1)
aCounter(45)
let anotherCounter = gameCounter()
anotherCounter(1)
anotherCounter(10)
anotherCounter(150)
print("aCounter Below")
aCounter(4)
// Bai Tap
extension String {
func modify(a: String -> String) -> String {
return a(self)
}
}
func firstLetter(b: String) -> String {
return "\(b[b.startIndex])"
}
let value = "Swift".modify(firstLetter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment