Last active
March 20, 2017 12:28
-
-
Save pd3v/bebd3876973c30128441 to your computer and use it in GitHub Desktop.
Generic Adding Function for scalar types and collections (Arrays and Dictionaries)
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 | |
protocol SummableType { | |
func +(lhs: Self, rhs: Self) -> Self | |
} | |
extension Int: SummableType {} | |
extension Float: SummableType {} | |
extension Double: SummableType {} | |
extension String: SummableType {} | |
// Generic func for scalar types | |
func add<T: SummableType>(op1: T, _ op2: T) -> T { | |
return op1 + op2 | |
} | |
// Assuming that collections add collection 2 to collection 1 because string adding (concatenation) is not commutative | |
// Generic overloading func for Arrays. | |
func add<T: SummableType>(var arr1: [T], _ arr2: [T]) -> [T] { | |
let arraySequenced: AnySequence<(index: Int, element: T)> | |
let arraySizeDiff = arr1.count - arr2.count | |
arraySequenced = arraySizeDiff >= 0 ? arr1.enumerate().dropLast(arraySizeDiff) : arr1.enumerate().dropFirst(0) | |
for (k, v) in arraySequenced { | |
arr1[k] = v + arr2[k] | |
} | |
arr1.appendContentsOf(arr2.dropFirst(arr2.count + arraySizeDiff)) | |
return arr1 | |
} | |
// Generic overloading func for Dictionaries | |
func add<U, T: SummableType>(var dict1: [U:T], _ dict2: [U:T]) -> [U:T] { | |
for (k, v) in dict1 { | |
if (dict2.indexForKey(k) != nil) { | |
dict1.updateValue(v + dict2[k]!, forKey: k) | |
} | |
} | |
for (k, v) in dict2 { | |
if (dict1.indexForKey(k) == nil) { | |
dict1.updateValue(v, forKey: k) | |
} | |
} | |
return dict1 | |
} | |
let ints = add(1, 3) // 4 | |
let strings = add("Hello ", "world!") // "Hello world!" | |
let doubles = add(1.1, 1) // 2.1 | |
let stringArrays = add(["H", "t", "al", "!"], ["ello", "o", "l"]) // ["Hello", "to", "all", "!"] | |
let numbersDict = add([1: 5.12, "2": 2, "3": 5, "4": 4, "stuff": 101], [1: -1.12, "3": -3, "2": -2, "6": 6]) // [1:4, "2":0, "3":2, "4":4, "stuff": 101, "6":6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment