> On Jul 18, 2017, at 10:33, Vladimir.S via swift-users <swift-users@swift.org>
> wrote:
>
> On 17.07.2017 4:51, Glen Huang via swift-users wrote:
>> Thanks for the code sample and link, but if I’m not wrong, this pattern
>> doesn’t allow heterogeneous items.
>
> Support the question. Trying to understand if we can have something like
> [AnyHashable] for our custom protocol(with associated type) or AnyHashable
> has a very special support from compiler and we can use only [Any] or such
> kind of wrapper:
>
> struct AnyMyProtocol {
> let actualInstance: Any
> init<T: MyProtocol>(_ instance: T) { actualInstance = instance}
> }
>
> let instances: [AnyMyProtocol] = [AnyMyProtocol(...), AnyMyProtocol(...)]
>
> if let some = instances[0].actualInstance as?
> SpecificImplementationOfMyProtocol {
> // use 'some' as SpecificImplementationMyProtocol instance
> // seems like no way to refer to just MyProtocol
> }
AnyHashable is special, sorry. You'll have to use this sort of indirect
unwrapping instead. You can write a little convenience method for it though, if
you want:
extension AnyMyProtocol {
func get<T: MyProtocol>(as: T.Type) -> T? {
return self.actualInstance as? T
}
}
if let some = instances[0].get(as: SpecificImplementationOfMyProtocol.self) {
// use 'some' here
}
Jordan
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users