Skip to content

Instantly share code, notes, and snippets.

@nhathm
Created March 31, 2019 22:19
Show Gist options
  • Select an option

  • Save nhathm/6658ff2b9124d1ac44d63de4ba6a3153 to your computer and use it in GitHub Desktop.

Select an option

Save nhathm/6658ff2b9124d1ac44d63de4ba6a3153 to your computer and use it in GitHub Desktop.
import Foundation
@dynamicCallable
class DynamicCalculator {
func dynamicallyCall(withArguments args: [Int]) -> Int {
return args.reduce(0, +)
}
func dynamicallyCall(withKeywordArguments args: KeyValuePairs<String, Int>) -> Int {
let sum = args.reduce(0) {
if $1.key == "plus" {
return $0 + $1.value
} else if $1.key == "minus" {
return $0 - $1.value
} else {
return $0
}
}
return sum
}
}
let dynamicCal = DynamicCalculator()
dynamicCal(1, 2, 3) // 1 + 2 + 3 = 6
dynamicCal(minus: 9, plus: 2, 3) // -9 + 2 + 0 (because last argument "3" don't have "key" so it will be ignored (else case))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment