We can add extensions to a generic type conditionally if the type conforms to a protocol. For example, if we wanted to add a sum() method to our generic List type only if the type for T conforms to the numeric protocol, we could do this as follows:
extension List where T: Numeric { func sum () -> T { return items.reduce (0, +) } }
This extension will add the sum() method to any List instance where the T type conforms to the numeric protocol. This means that the list instance in the previous example, where the list was created to hold String types, would not receive this method.
In the following code, where we create an instance of the List type that contains integers, the instance will receive sum() and can be used as shown:
var list2 = List<Int>() list2.add(item: 2) list2.add(item: 4) list2.add(item...