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

Glen Huang heyhgl at gmail.com
Wed Jul 19 00:36:18 CDT 2017


Do you think if there will be any evolution proposal to address this limitation? Or it’s an inherent tradeoff that is unlikely to be changed?

> On 19 Jul 2017, at 8:49 AM, Jordan Rose <jordan_rose at apple.com> wrote:
> 
> 
> 
>> On Jul 18, 2017, at 10:33, Vladimir.S via swift-users <swift-users at swift.org <mailto: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/20170719/4b1dac9a/attachment.html>


More information about the swift-users mailing list