Swift 为什么我的生成器协议(protocol)扩展不起作用?

标签 swift swift-extensions swift-protocols

我认为我对 Swift 类型/协议(protocol)/泛型的认知已经溢出了。我一直在使用扩展“输入流字节”的模式,方法如下:

extension GeneratorType where Element == UInt8 {
    func foobar()  {
        ...
    }
}

它在过去适用于简单的事情。今天我正在玩以下内容:

protocol Unpackable {
    static func unpack(inout input:IndexingGenerator<[UInt8]>) -> Self
}

extension UInt8:Unpackable {
    static func unpack(inout input:IndexingGenerator<[UInt8]>) -> UInt8 {
        return input.next()!
    }
}

extension UInt16:Unpackable {
    static func unpack(inout input:IndexingGenerator<[UInt8]>) -> UInt16 {
        return UInt16(input.next()!) | (UInt16(input.next()!) << 8)
    }
}

工作正常。但如果我尝试将两者放在一起,例如

extension GeneratorType where Element == UInt8 {
    func unpackAll() -> (UInt8, UInt16) {
        return (UInt8.unpack(&self), UInt16.unpack(&self))
}

然后我收到以下错误:

Cannot convert value of type 'Self' to expected argument type 'IndexingGenerator<[UInt8]>'

IndexingGenerator 不符合 GeneratorType 吗?它的Element不是UInt8吗?使用IndexingGenerator时出现错误吗?我无法将参数类型指定为 GeneratorType(尽管我真的很希望能够)。

我仍在等待 Swift 类型的灯泡闪烁。有时候我真的很喜欢这门语言。其他时候,我感觉我在对我的狗大喊大叫,试图让他过来,而他只是盯着我一动不动,然后转身沿着街道追去。

最佳答案

试试这个:

extension GeneratorType where Element == UInt8 {
    func unpackAll() -> (UInt8, UInt16)? {
        guard let _self = self as? IndexingGenerator<[Element]> else { return nil }
        var vSelf = _self
        return (UInt8.unpack(&vSelf), UInt16.unpack(&vSelf))
    }
}

更新:

protocol Unpackable {
    static func unpack<T : GeneratorType where T.Element == UInt8>(inout input:T) -> Self
}

extension UInt8: Unpackable {
    static func unpack<T : GeneratorType where T.Element == UInt8>(inout input: T) -> UInt8 {
        return input.next()!
    }
}

extension UInt16: Unpackable {
    static func unpack<T : GeneratorType where T.Element == UInt8>(inout input: T) -> UInt16 {
        return UInt16(input.next()!) | (UInt16(input.next()!) << 8)
    }
}

extension GeneratorType where Element == UInt8 {
    mutating func unpackAll() -> (UInt8, UInt16) {
        return (UInt8.unpack(&self), UInt16.unpack(&self))
    }
}

关于Swift 为什么我的生成器协议(protocol)扩展不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35879396/

相关文章:

swift - 使用起始日期和起始日期过滤数组

swift - 更新到 Swift 3 时,参数标签与任何可用的重载错误不匹配

swift - 交换键和值的字典扩展 - Swift 4.1

Swift - 指定符合泛型类型参数的协议(protocol)

ios - 设备旋转动画在 iOS 10 中不起作用

ios - Swift - 每 50 次后使用 sleep 者运行 1000 个异步任务 - 如何通信 btw DispatchGroups

swift - 如何扩展接受数组通用元素的类型?

ios - 从 Objective-C 访问 Swift 扩展

swift - 在 Swift 协议(protocol)上引用静态变量的正确方法是什么?

swift - Swift 中 'get' 和 'get set' 的区别