[swift-evolution] Overloading Generic Types

David Sweeris davesweeris at mac.com
Wed Feb 22 15:27:51 CST 2017


> On Feb 22, 2017, at 1:22 PM, David Sweeris <davesweeris at mac.com> wrote:
> 
>> 
>> On Feb 22, 2017, at 12:21 PM, Huon Wilson <huon at apple.com <mailto:huon at apple.com>> wrote:
>> 
>> 
>>> On Feb 22, 2017, at 10:20, David Sweeris via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>> 
>>> What if we extended that to any type that’s ExpressibleByNilLiteral & Equatable?
>> 
>> Note that this is not how the Unsafe*Pointer optimization works: in that case, the type Unsafe*Pointer is not ExpressibleByNilLiteral, it just has some spare/guaranteed-to-be-unused sentinel values in its representation, that the compiler knows about. This also works for types like `enum X { case A, B }`: an optional like X? (and X??, all the way up to 254 ?’s) is also represented as a single byte, because there’s spare values that the compiler knows won't be used by valid instances of X.
>> 
>> Converting valid instances  to .none would break round-tripping: Optional(x)! would sometimes fail, if x was the sentinel value. This seems likely to cause generic code to stop working.
> 
> Oh, hey, yeah, good point! I should’ve thought about that bit more first. Would a `HasInvalidBitPattern` protocol work? 
> protocol HasInvalidBitPattern {
>     /// An unreachable bit pattern. Very Bad Things are very likely to happen if this represents a valid value.
>     static var invalidBitPattern: Self {get} // probably use some private init to create this, or some other mechanism that doesn’t get exposed to the client
> }
> Then, the special-case Optional definition would be:
> enum Optional<T> : ExpressibleByNilLiteral where T: HasInvalidBitPattern & Equatable {
>     case some(T)
>     init(_ value: T) { self = .some(value) }
>     init(nilLiteral: ()) { self = .some(T.invalidBitPattern) }
>     var case none: (matches: Bool, associatedValue: Void) {
>         switch self {
>         case .some(let value): return (value == T.invalidBitPattern, ())
>         }
>     }
> }

(Regardless of exactly how it could be done, though, my point was that it at least seems like removing the compiler magic around `Optional<Unsafe*Pointer>` would be an application for being able to overload the storage of a generic type.)

- Dave Sweeris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170222/50bb2971/attachment.html>


More information about the swift-evolution mailing list