[swift-evolution] Generic parameters in "as?" checks

Charles Srstka cocoadev at charlessoft.com
Wed Jan 20 22:43:41 CST 2016


Currently, generic types can be hard to work with in certain cases; particularly if you want to check if an object belongs to a type that has generic parameters.

I’m wondering if it would be completely unreasonable to ask for the ability to introduce a generic parameter into an as? check, and have it treated the way a generic type would be treated in a generic function. Using Array as a convenient generic type that’s easy to create, let’s suppose we want to check if some random object is a array containing some type that we don’t care what type it is, as long as it’s a subclass of some type, conforms to some protocol, etc.

Something like this:

class Foo {
	required init() {}
	func doAFooThing() {}
}
class Bar: Foo {
	required init() { super.init() }
	func doABarThing() {}
}

if let arr = someObject as? Array<T: Foo> {
	for eachFoo in arr {
		T.doAFooThing()
		// but T.doABarThing() would not work
       }
	
	array.append(T())
}

Or perhaps, if we need angle brackets to be somewhere, something like this:

if let arr = someObject as? <T: Foo> Array<T> {
	…
}

Is this a feasible thing to ask for?

(Apologies if there’s already a way to do this; I was looking for one without success.)

Charles



More information about the swift-evolution mailing list