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

Slava Pestov spestov at apple.com
Wed Jul 19 01:34:36 CDT 2017


Hopefully we will one day have generalized existentials which would at least allow a heterogeneous array of protocols with an associated type; however it is not clear how such an existential could conform to Hashable in a general way, given that Hashable implies Equatable which has a Self requirement.

Slava

> On Jul 18, 2017, at 10:36 PM, Glen Huang via swift-users <swift-users at swift.org> wrote:
> 
> 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 <mailto: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
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170718/42ebb662/attachment.html>


More information about the swift-users mailing list