[swift-evolution] Intended behavior of typealiases in extensions?

Jens Persson jens at bitcycle.com
Sun Jul 30 18:08:16 CDT 2017


Typealiases in extensions currently does not work as expected or intended,
as can be demonstrated by the following example:

struct S<A> {
    var hmm: (A, B, C)
}
extension S where A == Bool {
    typealias B = A
    static func printB() { print(B.self) }
}
extension S where A == Float {
    typealias C = A
    static func printC() { print(C.self) }
}
let a = S(hmm: ("strange", true, Float(42.1)))
dump(a)

The above program will compile (!) and print:
▿ VectorAttempt4_Xc9b4.S<Swift.String>
  ▿ hmm: (3 elements)
    - .0: "strange"
    - .1: true
    - .2: 42.0999985

(SR-5440)

Here, the intended behavior would most probably involve a compile time
error for the declaration of `hmm: (A, B, C)`.

But in the following example, it is not that easy to guess the intended
behavior, and so I'd like to ask for your thoughts about it:

protocol P {
    associatedtype A
    typealias B = Int
}
extension P where A == Bool {
    typealias B = Float // Compiles, but should it?
}
extension P where A == Double {
    typealias B = String // ERROR: Invalid redeclaration of `B`
}

(SR-5392)

Note that Bool, Int, Float, Double and String can be any types; ie the
topmost overloaded-typealias-in-an-extension will always compile but the
rest will fail.

So, should both compile (thus allow overloading of `B`) or should both be
considered redeclarations?

I (naively) think it would be nice if both compiled, ie if it was possible
to overload associated types in constrained extensions, since it could open
up some interesting possibilities (or perhaps only a can of worms?).

/Jens
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170731/f6757542/attachment.html>


More information about the swift-evolution mailing list