I take it that your main aim is to hold a collection of objects conforming to some protocol, add to this collection and delete from it. This is the functionality as stated in your client, "SomeClass". Equatable inheritance requires self and that is not needed for this functionality. We could have made this work in arrays in Obj-C using "index" function that can take a custom comparator but this is not supported in Swift. So the simplest solution is to use a dictionary instead of an array as shown in the code below. I have provided getElements() which will give you back the protocol array you wanted. So anyone using SomeClass would not even know that a dictionary was used for implementation.
Since in any case, you would need some distinguishing property to separate your objets, I have assumed it is "name". Please make sure that your do element.name = "foo" when you create a new SomeProtocol instance. If the name is not set, you can still create the instance, but it won't be added to the collection and addElement() will return "false".
protocol SomeProtocol {
var name:String? {get set} // Since elements need to distinguished,
//we will assume it is by name in this example.
func bla()
}
class SomeClass {
//var protocols = [SomeProtocol]() //find is not supported in 2.0, indexOf if
// There is an Obj-C function index, that find element using custom comparator such as the one below, not available in Swift
/*
static func compareProtocols(one:SomeProtocol, toTheOther:SomeProtocol)->Bool {
if (one.name == nil) {return false}
if(toTheOther.name == nil) {return false}
if(one.name == toTheOther.name!) {return true}
return false
}
*/
//The best choice here is to use dictionary
var protocols = [String:SomeProtocol]()
func addElement(element: SomeProtocol) -> Bool {
//self.protocols.append(element)
if let index = element.name {
protocols[index] = element
return true
}
return false
}
func removeElement(element: SomeProtocol) {
//if let index = find(self.protocols, element) { // find not suported in Swift 2.0
if let index = element.name {
protocols.removeValueForKey(index)
}
}
func getElements() -> [SomeProtocol] {
return Array(protocols.values)
}
}