Created
March 31, 2019 22:19
-
-
Save nhathm/6658ff2b9124d1ac44d63de4ba6a3153 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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