protocol A {}
protocol B {
var a: A { get }
}
struct StructA: A {}
struct StructB {
var a: StructA
}
extension StructB: B {}
这会产生错误:
Type 'StructB' does not conform to protocol 'B'
StructA
已经符合协议(protocol)A
,StructB
的属性a
返回StructA
类型。这似乎是一个符合协议(protocol) B 的类型。
但为什么呢?
Xcode 版本 7.3,Swift 版本为 2.2
最佳答案
为了更好地说明您当前代码的问题,假设您有一个 StructC : A
。
你的协议(protocol) B
说你可以将 StructC
分配给 a
(因为它符合 A
)——但是 StructB
表示您不能将 StructC
分配给 StructA
类型。因此 StructB
不符合 B
。
解决方案是将 a
的类型从 StructA
更改为 A
as Rahul says ,或者更好的是,您可以使用泛型。
使用泛型的优势在于,一旦您使用给定的 a
创建了 StructB
– 该属性的类型将由 Swift 推断,从而为您提供更好的类型安全性。例如,一旦您将 StructA
分配给它,它的类型就会是 StructA
。如果您将 StructC
分配给它,它的类型将为 StructC
。
为此,我们只需将associatedtype
添加到协议(protocol)B
。这将定义一个“占位符”类型,然后我们可以在符合 B
的类型中实现该类型。然后,我们可以在 StructB
中定义泛型 T
,它将提供 AType
的“实现”——确保它符合 A
。因此,我们现在可以自由地将 StructA
或 StructC
分配给 a
,而不会失去类型安全性。
protocol A {}
protocol B {
// new associated type to hold the type of "a" which conforms to A
associatedtype AType:A
var a: AType { get }
}
struct StructA: A {}
struct StructC:A {}
// define the new generic T which conforms to A
struct StructB<T:A> {
// define the type of a as the generic T, which conforms to A (and thus conforms with the protocol)
var a : T
}
extension StructB: B {}
let s = StructB(a: StructA())
s.a // "a" is now of type StructA
let s1 = StructB(a: StructC())
s1.a // "a" is now of type StructC
关于Swift:类型不符合协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36812250/