6

在我的 swift 项目中,我有一个使用协议继承的情况,如下所示

protocol A : class{

}

protocol B : A{

}

我接下来要实现的是声明另一个具有关联类型的协议,该类型必须继承自协议A。如果我尝试将其声明为:

protocol AnotherProtocol{
    associatedtype Type : A
    weak var type : Type?{get set}
}

AnotherProtocol它编译时没有错误,但在以下情况下尝试采用时:

class SomeClass : AnotherProtocol{

    typealias Type = B
    weak var type : Type?
}

编译失败,错误声明SomeClass不符合AnotherProtocol. 如果我理解正确,这意味着在我尝试声明并询问您如何声明从协议继承的关联类型时B 不采用?AA

我基于以下场景编译得很好的事实做出了上述假设

class SomeDummyClass : B{

}

class SomeClass : AnotherProtocol{

    typealias Type = SomeDummyClass
    weak var type : Type?
}
4

1 回答 1

5

这很有趣。看来,一旦您在给定协议中限制了 an 的类型associatedtype您就需要在该协议的实现中提供一个具体类型(而不是另一个协议类型)——这就是您的第二个示例有效的原因。

如果您删除A对关联类型的约束,您的第一个示例将起作用(减去关于无法weak在非类类型上使用的错误,但这似乎不相关)。

话虽如此,我似乎找不到任何文件来证实这一点。如果有人能找到支持这一点的东西(或完全反驳它),我很想知道!

要使您当前的代码正常工作,您可以使用泛型。这实际上会用一块石头杀死两只鸟,因为您的代码现在都将编译,并且您将受益于泛型带来的增加的类型安全性(通过推断您传递给它们的类型)。

例如:

protocol A : class {}
protocol B : A {}

protocol AnotherProtocol{
    associatedtype Type : A
    weak var type : Type? {get set}
}

class SomeClass<T:B> : AnotherProtocol {
    typealias Type = T
    weak var type : Type?
}

编辑:上面的解决方案似乎不适用于您的特定情况,因为您想避免使用具体类型。我会把它留在这里,以防它对其他人有用。


在您的特定情况下,您可以使用类型擦除来为您的B协议创建伪具体类型。Rob Napier 有一篇关于类型擦除的精彩文章。

在这种情况下,这是一个有点奇怪的解决方案(因为类型擦除通常用于用 包装协议associatedtypes),而且它也绝对不如上述解决方案,因为您必须为每个方法重新实现一个“代理”方法你的A&B协议——但它应该适合你。

例如:

protocol A:class {
    func doSomethingInA() -> String
}

protocol B : A {
    func doSomethingInB(foo:Int)
    func doSomethingElseInB(foo:Int)->Int
}

// a pseudo concrete type to wrap a class that conforms to B,
// by storing the methods that it implements.
class AnyB:B {

    // proxy method storage
    private let _doSomethingInA:(Void)->String
    private let _doSomethingInB:(Int)->Void
    private let _doSomethingElseInB:(Int)->Int

    // initialise proxy methods
    init<Base:B>(_ base:Base) {
        _doSomethingInA = base.doSomethingInA
        _doSomethingInB = base.doSomethingInB
        _doSomethingElseInB = base.doSomethingElseInB
    }

    // implement the proxy methods
    func doSomethingInA() -> String {return _doSomethingInA()}
    func doSomethingInB(foo: Int) {_doSomethingInB(foo)}
    func doSomethingElseInB(foo: Int) -> Int {return _doSomethingElseInB(foo)}
}

protocol AnotherProtocol{
    associatedtype Type:A
    weak var type : Type? {get set}
}

class SomeClass : AnotherProtocol {
    typealias Type = AnyB
    weak var type : Type?
}

class AType:B {
    // implement the methods here..
}
class AnotherType:B {
    // implement the methods here..
}

// your SomeClass instance
let c = SomeClass()

// set it to an AType instance
c.type = AnyB(AType())

// set it to an AnotherType instance
c.type = AnyB(AnotherType())

// call your methods like normal
c.type?.doSomethingInA()
c.type?.doSomethingInB(5)
c.type?.doSomethingElseInB(4)

您现在可以使用该AnyB类型来代替使用B协议类型,而无需对其进行任何类型限制。

于 2016-04-26T16:13:48.517 回答