Creating collections of mixed types

Using the code we have written so far, we can create an Array that contains both an Int and a ChattyStruct:

var talkativesArray: [Talkative] = [] 
talkativesArray.append(anon)
talkativesArray.append(42)

In the code above, it can be seen that an Array (or any other collection) can be of type <SomeProtocol>, rather than be restricted to a specific type.

This means that we can perform any operation with the elements of talkativesArray that are specified by the protocol:

for entity in talkativesArray 
{
entity.sayHi()
}

Note that we cannot use any methods that are not in the protocol specification, since all we know about the contents of the array is that each element conforms to the given protocol; at least, not without some extra work. To use methods specific to the specific types, we must first try to cast the element to that type:

if let entity = entity as? Int 
{
print("... and twice \(entity) makes \(entity * 2)")
}