In addition to being able to specify generic types, you can use generics to build functions that are both widely applicable and strongly typed. In this recipe, we will use generics with functions.
How to do it...
We will use generics to create a function to help with placing values into a dictionary:
- Create a generic function that inserts the same value into a dictionary for multiple keys:
func makeDuplicates<ItemType>(of item: ItemType,
withKeys keys: Set<String>) -> [String: ItemType] {
var duplicates = [String: ItemType]()
for key in keys {
duplicates[key] = item
}
return duplicates
}
- Use this function, passing in a single value and multiple keys, and the value is stored against each of the given keys:
let awards: Set<String> = ["Best Director",
"Best Picture",
"Best Original Screenplay",
"...