【发布时间】:2014-07-14 08:40:16
【问题描述】:
我想尝试用纯 swift 实现消息包。在我来到 Array 之前,一切都很顺利。
我的方法是实现一个名为MsgPackMarshable 的协议,这是扩展的原始类型:
//Protocol
protocol MsgPackMarshable{
func msgpack_marshal() -> Array<Byte>
}
//Implementation for some types
extension UInt8 : MsgPackMarshable{
func msgpack_marshal() -> Array<Byte>{
return [0xcc, self]
}
}
extension UInt16 : MsgPackMarshable{
func msgpack_marshal() -> Array<Byte>{
let bigEndian: UInt16 = self.bigEndian
return [0xcd, Byte((bigEndian & 0xFF00) >> 8), Byte(bigEndian & 0x00FF)]
}
}
extension UInt32 : MsgPackMarshable{
func msgpack_marshal() -> Array<Byte>{
let bigEndian: UInt32 = self.bigEndian
return [0xce, Byte((bigEndian & 0xFF000000) >> 24), Byte((bigEndian & 0xFF0000) >> 16), Byte((bigEndian & 0xFF00) >> 8), Byte(bigEndian & 0x00FF)]
}
}
我在扩展Array 时遇到了一些麻烦。我想动态验证数组的类型是否实现了MsgPackMarshable 协议:
extension Array: MsgPackMarshable{
func msgpack_marshal() -> Array<Byte>{
for item in self{
//How to check type here?
}
return []
}
}
由于Array 是swift 中的结构,我想避免重新定义嵌入数组的新类型Array<MsgPackMarshable>。
【问题讨论】:
-
与您的阵列问题无关,但请注意,对于 UInt16/32,您必须右移 8、16 或 24,而不是 2、3 或 4。
-
我太笨了 :) 谢谢!
标签: arrays generics dictionary swift