[swift-evolution] 'T != Type' in where clause

Douglas Gregor dgregor at apple.com
Wed Mar 1 10:49:47 CST 2017


> On Mar 1, 2017, at 1:55 AM, Jonathan Hull <jhull at gbis.com> wrote:
> 
> What I would like is a way to specialize a generic function in a block of code: (Strawman syntax)
> 
> 	if T is Int.self {
> 		//In this block of code T == Int
> 	}
> 
> It seems to me that the compiler might even be able to optimize this without a branch.  If there is a return in the block, then it might even be able to throw away all the code after it for the Int version of the function.

We’ve been calling this “type refinement”. Essentially, within some lexical context (the “if” here) we can assert additional properties on a type or one specific (constant) values and take advantage of those properties, as you’ve done with T == Int.

It’s a plausible language feature, and could be useful. There’s certainly some precedent for it: C++17 adds something similar with “constexpr if”, albeit in their non-separately-type-checked template instantiation model.

It’s a nontrivial language feature that’s well out of scope for Swift 4.

	- Doug



More information about the swift-evolution mailing list