Dictionaries
Swift generics allow for multiple type parameters and for complex sets of restrictions on them. These let you use generic types and protocols with associated types to model complex algorithms and data structures. A straightforward example of this is dictionaries.
Dictionary has two type parameters in the comma-separated generic parameter list that falls between the angle brackets, as you can see in its declaration:
struct Dictionary<Key: Hashable, Value> // etc..
Key and Value represent the types of the dictionary’s keys and values. But the annotation on Key, Key : Hashable, says more. Everything after that colon is a type constraint. A type constraint indicates a required supertype, and/or a required protocol or list of protocols, for any type that will serve as the argument for that type parameter.
For instance, the type constraint for Dictionary requires that any type serving as the key for the dictionary be hashable, because the dictionary is a hash map and must hash its keys to enable fast lookup.
To instantiate types such as Dictionary with multiple type parameters, simply provide a comma-separated type argument list:
let intNames: Dictionary<Int, String> = [42: "forty-two"]
As with arrays, dictionaries get some special treatment in Swift since they’re built-in and so common. You’ve already seen the shorthand notation [Key: Value], and you can also use type inference:
let intNames2: [Int: String] = [42: "forty-two", 7: "seven"] let intNames3 = [42: "forty-two", 7: "seven"]