Swift: Array property with elements conforming to a class and multiple protocols simultaneously
Thanks to @SebastianDressler and @Mike-S I found out that there isn't a straightforward way how to express this in Swift.
What you can do though is to constrain the type of the item you want to add to the array like this:
func addItem<T where T: BaseClass, T: Protocol1, T: Protocol2>(item: T) {
self.array.append(item)
}
Casting the items from the array when its type is defined as the one of the base class of the protocols is not possible, because the compiler doesn't see any relation between those types.
In order to be able to cast to the base class or to one of the protocols, it is necessary to declare the type as AnyObject
.
var array: [AnyObject] = []
And casting to the protocols only works when they are annotated with @objc
(see https://stackoverflow.com/a/24318145/670119).