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

Dave Abrahams dabrahams at apple.com
Wed Mar 1 14:59:13 CST 2017


on Wed Mar 01 2017, Douglas Gregor <swift-evolution at swift.org> wrote:

>> 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.

Huh?  This totally works:

  extension Optional {                                                                                                                            
    func goo() -> Int { 
      return Wrapped.self is Int.Type ? 1 : 0
    }                                                                                    
  }

  func rue() -> Int {
    return (nil as Bool?).goo() + (nil as Int?).goo()
  }

  /* rue optimizes down to:

          .private_extern	__TF1x3rueFT_Si
          .globl	__TF1x3rueFT_Si
          .p2align	4, 0x90
  __TF1x3rueFT_Si:
          pushq	%rbp
          movq	%rsp, %rbp
          movl	$1, %eax
          popq	%rbp
          retq
  */

  print(rue())

What am I missing?
-- 
-Dave



More information about the swift-evolution mailing list