Swift:类型不符合协议(protocol)

标签 swift swift2 protocols

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)AStructB 的属性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 。因此,我们现在可以自由地将 StructAStructC 分配给 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/

相关文章:

string - 如何在 Swift 2.0 中为 URL 使用 stringByAddingPercentEncodingWithAllowedCharacters()

ios - 使用if/else语句返回可观察到的值不适用于RxSwift flatMap

ios - 错误 : Value of type '[String]' has no member 'objectAtIndex' while implementing UISearchController

ios - swift 2 : NSData(contentsOfURL:url) returning nil

ios - 使用委托(delegate)/协议(protocol)将数据传递给第三方 View Controller

ios - 将 Int 范围数组快速转换为字符串数组

ios - 允许用户仅在 Swift 中输入下一个可用的文本字段

google-places-api - 无法使用 Xcode 7/iOS9 使用 Google Maps API 在路径错误时加载优化模型

swift - 协议(protocol)扩展中的方法永远不会被调用,加上书中的错误

ios - Swift:如何为其委托(delegate)创建具有泛型类型的自定义重写 UITableView?