【发布时间】:2016-03-08 22:35:26
【问题描述】:
我认为我对 Swift 类型/协议/泛型的认知已经溢出。我一直在使用扩展“输入流字节”的模式,方法是:
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 吗?它的元素不是 UInt8 吗?是使用 IndexingGenerator 的错误吗?我无法将参数类型指定为 GeneratorType(尽管我真的很想这样做)。
我仍在等待 Swift 类型的灯泡闪烁。有些日子我真的很喜欢这种语言。其他时候,我觉得我在对我的狗大喊大叫,试图让他过来,他只是盯着我一动不动,然后转身沿着街追。
【问题讨论】:
-
“IndexingGenerator 不符合 GeneratorType” 是的,但不是每个 GeneratorType 都是 IndexingGenerator。
-
我提出
IndexingGenerator<[UInt8]>的论点只是因为我不知道如何更通用地做到这一点。老实说,我不在乎它是一个 IndexingGenerator。我可以使用任何类型的生成器,只要它生成 UInt8。有没有办法让参数成为适当规范的协议? -
声明一个符合
GeneratorType的new 协议并以某种方式限制符合类型以具有UInt8的元素的技巧吗? -
解决方案与 AnyGenerator 有关系吗?
标签: swift swift-extensions swift-protocols