How to specialize parent protocol's associatetype in sub-protocol?


(刘锋炜(kAzec)) #1

Hi Swift users,

I’m defining a sub-protocol inheriting from parent protocol with associatedtype, and I want to specialized the associatedtype to certain concrete type.

For example,

protocol Foo {
    associatedtype Bar
    
    static var bar: Bar { get }
}
    
protocol A: Foo {
    // I want `Bar` to be `Int`.
    static var a: Int { get }
    static var bar: Int { get }
}

extension A {
    typealias Bar = Int
}

I want any class/struct adopting protocol `A` having associatedtype `Bar` specialized to Int. However, I found that structs adopting `A` are still capable of override it.

extension A {
    static var bar: Int {
        return a
    }

    static func test() {
        print(bar)
    }
}

struct AStruct: A {
    static let a: Int = 0
    static let bar: Bool = false // Bar is now Bool
    // static let bar: Int now becomes invisible.
}

AStruct.test() // prints 0

The code above gave same result on both Swift 2.2(Xcode 7.3.1) and Swift 3.0(Xcode 8 beta 3).

It’s this expected behavior? Or am I'm getting something wrong here? What about specializing parent’s associatedtype to certain generic type with newly introduced associatedtype? For example,

protocol B: Foo {
    associatedtype T
    static var bar: Array<T> { get }
}

extension B {
    typealias Bar = Array<T>
}

Any idea would be appreciated.

Thanks

Fengwei