【问题标题】:Swift protocols and equatableSwift 协议和 equatable
【发布时间】:2017-06-26 23:21:10
【问题描述】:

我仍在学习如何使用对象数组来实现具有关联类型的协议。

我有以下协议:

public protocol Word : Equatable, Hashable { // compiles

    associatedtype WordType : Equatable

    var moreWords: [WordType] { get }

}

public protocol WordDataSource { // compiles

    associatedtype SomeWord : Word

    func findWord(spelling: String) -> SomeWord?

}

我有 WordAWordBWordC 都实现了 Word 和子类化 NSObject

基本上,我想使用实现 Word 类的不同类来实现数据源协议。这是我想写的那种代码,但显然它不能编译。

class MyDataSource : WordDataSource {

    func findWord(spelling: String) -> SomeWord? {

         if conditionA {
             return WordA()
         }
         if conditionB {
             return WordB()
         } 
         if conditionA {
             return WordC()
         } 
    }

}

这在 Swift 中是否可行?我应该写什么来完成这项工作?

非常感谢您的帮助!

【问题讨论】:

    标签: swift protocols associated-types


    【解决方案1】:

    这是不可能的,而且是有原因的。让我们假设您的课程 MyDataSource 确实可以编译。现在,我们可以编写这样的代码:

    let fooWord = MyDataSource().findWord(spelling: "Foo") // Would return WordA instance
    let barWord = MyDataSource().findWord(spelling: "Bar") // Would return WordB instance
    

    但我们对这两种类型的了解只是它们属于SomeWord 类型。所以它们应该是可比的,因为Word 是可比的,对吧?

    但是它们是两种完全不同的类型,那么您怎么知道应该如何比较它们呢?看一下Equatable协议的定义:

    public static func ==(lhs: Self, rhs: Self) -> Bool

    您只能比较符合此协议的相同类型的两个对象。

    【讨论】:

      猜你喜欢
      • 2017-06-27
      • 1970-01-01
      • 2015-11-02
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      相关资源
      最近更新 更多