In the previous exercise, we saw how to create our own protocols. The Swift standard library includes many useful protocols that you can have your structures, classes, or enums conform to. A useful example is Hashable
.
The Hashable
protocol is used to make structs, classes, and enums able to be added to Set
s and Dictionaries
. To conform to Hashable
, a struct, class, or enum either needs to have a hashValue
property or to have only properties that already conform to Hashable
. Most basic Swift types conform to Hashable
. The following code won’t compile:
struct Resident { var name: String var age: Int var address: String var socialSecurityNum: String } let taxesByResident = [Resident: Double]() // ERROR: Type 'Resident' does not conform to protocol 'Hashable'
We can make this code compile by adding the Hashable
protocol to Resident
:
struct Resident: Hashable { let name: String let age: Int let address: String let socialSecurityNum: String } let taxesByResident = [Resident: Double]()
Hashable
is just one of many protocols in Swift! For more on common protocols, check out the link here to Apple’s documentation.
Instructions
Create a struct Store
that has a name
of type String
and a products
property of type [String]
.
Create a constant of type Store
named jaysPizza
and assign it to a store with a name
of “Jay’s Pizza” and products
["Pizza", "Soda", "Salad"]
.
Create a property named salesByStore
of type [Store: Double]
using type annotation, and assign it to a dictionary that maps jaysPizza
to 100. You should get a compiler error!
Make the Store
conform to Hashable
. The code should now compile!