[swift-evolution] AnyProtocol proposal

João Nunes joao3001 at hotmail.com
Thu Feb 11 08:08:39 CST 2016


Hello,


I have been thinking about a case that is missing completely from swift.


We have the AnyObject type to represent an Object of any type. 
I recently run upon a situation where i needed a type to represent any Protocol. A AnyProtocol Type would be useful for my case.


Example:


I have a generic class that needs to receive a protocol type. The code without the AnyProtocol is the following:
 






public class MulticastDelegate<T> {








	








	private var delegates = NSHashTable.weakObjectsHashTable()








	








	public init() {}








	








	public func addDelegate(delegate: T) {








		guard delegate is AnyObject else { return }








		delegates.addObject((delegate as! AnyObject))








	}
}


This code needs to “trust” that T is a protocol and also make sure T is an Object.

Example using AnyProtocol, if it existed:
public class MulticastDelegate<T:AnyProtocol> {


	


	private var delegates = NSHashTable.weakObjectsHashTable()


	


	public init() {}


	


	public func addDelegate(delegate: T) {




		delegates.addObject(delegate)


	}
}


Note that the protocol must be a class protocol. This could also be achieved with a where clause or AnyClassProtocol variant.


This example is also available on github: https://github.com/jonasman/MulticastDelegate


To extend my proposal, there might be cases where AnyStruct and AnyEnum would be usefull. I have no examples for these cases, but i believe someone might have it.
What are your thoughts, should I open a PR proposal?

João Nunes 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160211/55d36732/attachment.html>


More information about the swift-evolution mailing list