Bug: Generic type cannot check for nil

This is closely related to Generic types as generic constraints.

Indeed, if every generic type had an implicit protocol that abstracted all the capabilities of the type (or at least if things behaved as though there were such a protocol), then the idea proposed in that thread would work directly, without any extra complexity.

You could write, eg, extension Dictionary where Value: Optional, and it would work as expected.

And for this thread, once SE–03039: Unlock existentials for all protocols lands, then implicit protocols for generic types would make it possible to write this:

extension Optional {
  var isNil: Bool { self == nil }
}

func isNil<T>(_ value: T) -> Bool {
  return (value as? Optional)?.isNil ?? false
}

Or even just this, without extending Optional at all:

func isNil<T>(_ value: T) -> Bool {
  guard let x = value as? Optional else { return false }
  return x == nil
}

(That == is the _OptionalNilComparisonType version, because there is no Equatable constraint.)

1 Like