Skip to content

Instantly share code, notes, and snippets.

@scotteg
Last active August 29, 2015 14:06
Show Gist options
  • Save scotteg/e43fd06c8b15afdaf26e to your computer and use it in GitHub Desktop.
Save scotteg/e43fd06c8b15afdaf26e to your computer and use it in GitHub Desktop.
Example of a Swift function that takes a function as a parameter, nests functions, and returns a function
func formatNumberAsSpelledOutString(number: Any) -> String {
var numberString: String!
let spellOutFormatter = NSNumberFormatter()
spellOutFormatter.numberStyle = .SpellOutStyle
if number is Int {
let num = number as Int
numberString = spellOutFormatter.stringFromNumber(num)
} else if number is Double {
spellOutFormatter.minimumFractionDigits = 1
let num = number as Double
numberString = spellOutFormatter.stringFromNumber(num)
} else {
numberString = "NaN"
}
return numberString
}
func printOutSumOfNumber(var number1: Any, var andNumber number2: Any, withFormatter formatter: (Any) -> String) -> () -> () {
var result: String!
func addTwoIntegers(int1: Any, int2: Any) -> Int {
let num1 = int1 as Int
let num2 = int2 as Int
let sum = num1 + num2
return sum
}
func addTwoDoubles(int1: Any, int2: Any) -> Double {
let num1 = int1 as Double
let num2 = int2 as Double
let sum = num1 + num2
return sum
}
func printResult() {
println("The sum of \(formatter(number1)) and \(formatter(number2)) is \(result).")
}
switch (number1, number2) {
case (is Int, is Int):
number1 = number1 as Int
number2 = number2 as Int
let sum = addTwoIntegers(number1, number2)
result = formatter(sum)
case (is Int, is Double):
number1 = Double(number1 as Int)
number2 = number2 as Double
let sum = addTwoDoubles(number1, number2)
result = formatter(sum)
case (is Double, is Int):
number1 = number1 as Double
number2 = Double(number2 as Int)
let sum = addTwoDoubles(number1, number2)
result = formatter(sum)
case (is Double, is Double):
number1 = number1 as Double
number2 = number2 as Double
let sum = addTwoDoubles(number1, number2)
result = formatter(sum)
default:
result = formatter("")
}
return printResult
}
printOutSumOfNumber(1, andNumber: 0.23, withFormatter: formatNumberAsSpelledOutString)() // Prints "The sum of one and zero point two three is one point two three."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment