Hi
I have an array of protocols and would like to retrieve items from the array based on an enum. Something like this:
enum ServiceType: String {
case car
case boat
}
protocol ServiceDescriptor {
var contact: String { get }
var type: ServiceType { get }
}
struct CarService: ServiceDescriptor {
let contact: String
let type: ServiceType
}
struct BoatService: ServiceDescriptor {
let contact: String
let type: ServiceType
}
class Repair {
init(allowedRepairs: [ServiceDescriptor]) {
self.allowedRepairs = allowedRepairs
}
let allowedRepairs: [ServiceDescriptor]
subscript(type: ServiceType) -> ServiceDescriptor? {
get {
return allowedRepairs.first(where: { $0.type == type })
}
}
}
let carService = CarService(contact: "Fred", type: .car)
let boatService = BoatService(contact: "Jane", type: .boat)
let repair = Repair(allowedRepairs: [carService, boatService])
print(repair.allowedRepairs[type: ServiceType.boat]). // error
I end up with errors in Playgrounds as:
no exact matches in call to subscript
found candidate with type '(ServiceType) -> Array.SubSequence' (aka '(ServiceType) -> ArraySlice< ServiceDescriptor >')
The following works:
print(repair.allowedRepairs[0])
I'm obviously coming about this the wrong way, I wanted to avoid a dictionary i.e let allowedRepairs: [ServiceType: ServiceDescriptor]
because that would lend itself to assigning the wrong ServiceDescriptor
to a ServiceType
and it kinda duplicates the data.
Is there a another way to have a custom argument in subscript
instead of int
?
Many thanks