Learn

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, enums conform to. A useful examples is Hashable.

The Hashable protocol is used to make structs, classes, and enums able to be added to Sets 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

1.

Create a struct Store that has a name of type String and a products property of type [String].

2.

Create an instance of a Store named jaysPizza and assign it to a store with a name of “Jay’s Pizza” and products ["Pizza", "Soda", "Salad"].

3.

Create a property named salesByStore of type [String: Double] using type annotation, and assign it to a dictionary that maps jaysPizza to 100. You should get a compiler error!

4.

Make the Store conform to Hashable. The code should now compile!

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?