[swift-users] ⁨Is it possible to store a set of heterogeneous items with protocol?

Jordan Rose jordan_rose at apple.com
Tue Jul 18 19:49:24 CDT 2017



> On Jul 18, 2017, at 10:33, Vladimir.S via swift-users <swift-users at 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170718/b3dcca8b/attachment.html>


More information about the swift-users mailing list