Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.