类型开关模式

时间:2018-07-01 09:22:56

标签: swift generics

这是我追求的模式:

protocol A {
    associatedtype B
    var type: B.Type { get }
}

protocol P {}
struct X: P {}
struct Y: P {}
struct Z: P {}

struct SwitchP: A { // → error: type 'SwitchP' does not conform to protocol 'A'

    var someContext: Int

    var type: P.Type {
        switch someContext {
        case 1: return X.self
        case 2: return Y.self
        default: return Z.self
        }
    }
}

问题是如何在不引发↑编译时错误的情况下定义协议A

1 个答案:

答案 0 :(得分:0)

关于它的价值,请注意,切换类层次结构确实符合A,但这当然太局限了:

protocol A {
    associatedtype B
    var type: B.Type { get }
}

class C {}

class X: C {}
class Y: C {}
class Z: C {}

struct SwitchC: A {

    var someContext: Int

    var type: C.Type {
        switch someContext {
        case 1: return X.self
        case 2: return Y.self
        default: return Z.self
        }
    }
}

还请注意以下编译:

struct NotASwitchP: A {

    typealias B = P

    var type: P.Protocol { // ← compiles, but should it!?
        return P.self // now we can't return X.self
    }
}

...在我看来,这是一个编译器错误,这使得问题中的符合性SwitchP: A不可能:(