Created
June 3, 2016 18:21
-
-
Save leojkwan/00b1f8482274c71a861e9ff4370a4336 to your computer and use it in GitHub Desktop.
This file contains 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
struct Person { | |
var name:String | |
} | |
let leo = Person(name: "Leo") | |
let nicole = Person(name: "Nicole") | |
let leonardoButCalledLeo = Person(name: "Leo") | |
let ashton = Person(name: "Ashton") | |
extension Person: Equatable { | |
} | |
func == (lhs:Person, rhs: Person)-> Bool { | |
return lhs.name == rhs.name | |
} | |
extension Person: Hashable { | |
var hashValue: Int { | |
return name.hashValue | |
} | |
} | |
func findItemCountForArray<T:Hashable>(arr:[T]) -> [T: Int] { | |
// 1 | |
var countDict = [T: Int]() | |
for key in arr { | |
// 2 | |
if countDict[key] == nil { | |
countDict[key] = 0 | |
} | |
// 3 | |
countDict[key]! += 1 | |
} | |
return countDict | |
} | |
let arrayOfPeople = findItemCountForArray([leo,leonardoButCalledLeo,ashton,nicole]) | |
// Result: [{name "Leo"}: 2, {name "Ashton"}: 1, {name "Nicole"}: 1] | |
assert(leo == nicole) | |
// Result: error | |
assert(leo == leonardoButCalledLeo) | |
// Good |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment