【问题标题】:Swift minimum implementation for types conforming to protocols with default implementations符合具有默认实现的协议的类型的 Swift 最小实现
【发布时间】:2015-09-19 13:11:57
【问题描述】:

我正在尝试使我自己的类型符合CollectionType。随着 Swift 2.0 中引入的协议扩展,现在可以只实现所需实例方法的子集,同时自动实现所有其他方法。但是我需要提供的最小方法子集是什么?

【问题讨论】:

    标签: swift


    【解决方案1】:

    似乎最低要求是实现 Indexable 协议。这是一个例子,没有一个 可以省略属性/方法而不会导致编译器错误:

    struct MyCollectionType : CollectionType {
    
        var startIndex : Int { return 0 }
        var endIndex : Int { return 3 }
    
        subscript(position : Int) -> String {
            return "I am element #\(position)"
        }
    }
    

    默认实现SequenceType协议:

    let coll = MyCollectionType()
    for elem in coll {
        print(elem)
    }
    /*
    I am element #0
    I am element #1
    I am element #2
    */
    

    对于一个可变集合类型,下标必须是读/写的:

    struct MyCollectionType : MutableCollectionType {
    
        var startIndex : Int { return 0 }
        var endIndex : Int { return 3 }
    
        subscript(position : Int) -> String {
            get {
                return "I am element #\(position)"
            }
            set(newElement) {
                // Do something ...
            }
        }
    }
    

    Swift 3 更新: CollectionType 已重命名为 Collection,你必须实现一个额外的方法 其中“移动索引”(比较 A New Model for Collections and Indices):

    struct MyCollectionType : Collection {
    
        var startIndex : Int { return 0 }
        var endIndex : Int { return 3 }
    
        subscript(position : Int) -> String {
            return "I am element #\(position)"
        }
    
        func index(after i: Int) -> Int {
            guard i != endIndex else { fatalError("Cannot increment endIndex") }
            return i + 1
        }
    }
    

    【讨论】:

    • 非常感谢!但是像SequenceType 这样的其他情况呢?有什么通用的方法可以解决这个问题吗?
    • @Peter:这是一个有趣的问题,但我没有一个普遍的答案。我所做的只是从一个空实现开始:struct ABC : CollectionType { } 并在报告导航器中检查编译器消息。第一个错误是“错误:类型'ABC'不符合协议'Indexable'”。我不知道这种方法是否普遍有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多