Structs上的协议扩展导致编译错误"Self"约束为非协议类型

Chr*_*her 12 swift

我正在尝试将约束协议扩展应用于结构(Swift 2.0)并接收以下编译器错误:

类型'Self'约束为非协议类型'Foo'

struct Foo: MyProtocol {
    let myVar: String

    init(myVar: String) {
        self.myVar = myVar
    }
}

protocol MyProtocol {
    func bar()
}

extension MyProtocol where Self: Foo {
    func bar() {
        print(myVar)
    }
}

let foo = Foo(myVar: "Hello, Protocol")
foo.bar()
Run Code Online (Sandbox Code Playgroud)

我可以通过更改struct Foo来修复此错误,class Foo但我不明白为什么这样做.为什么我不能将where Self:约束协议作为结构?

Dan*_*hin 19

这是一种预期的行为,考虑struct到并不意味着继承:符号代表.

实现你所描述的东西的正确方法就像平等符号一样:

extension MyProtocol where Self == Foo {
    func bar() {
        print(myVar)
    }
}
Run Code Online (Sandbox Code Playgroud)

但这不能编译为某些愚蠢的原因,如:

相同类型的要求使通用参数Self非泛型

对于它的价值,您可以通过以下方式获得相同的结果:

protocol FooProtocol {
  var myVar: String { get }
}
struct Foo: FooProtocol, MyProtocol {
  let myVar: String
}

protocol MyProtocol {}
extension MyProtocol where Self: FooProtocol {
  func bar() {
    print(myVar)
  }
}
Run Code Online (Sandbox Code Playgroud)

哪里FooProtocol是假的protocol,只Foo应该延伸.

许多尝试使用extend标准库struct类型的第三方库(例如可选)都使用了与上面类似的解决方法.