[英]Swift extend UInt8 Array
我想扩展UInt8值的数组,所以我在Swift 3中编写了以下代码:
extension Array where Element: UInt8 {
}
但是我得到了这个错误:
类型'Self.Generator.Element'限制为非协议类型'UInt8'
那么我该如何解决呢?
语法Element: X
表示要对X
定义的Element
施加类型约束,其中X
必须是协议或派生Element
的类。 作为一种解决方法,如果您想构造Array
的扩展,该扩展仅适用于具有(值类型)元素UInt8
,则可以定义仅UInt8
符合的协议,并将此协议用作扩展中的类型约束。 例如
protocol MyType {}
extension UInt8: MyType {}
extension Array where Element: MyType {
// ...
}
在当前的实现中,扩展中的任何代码对Element
类型的了解仅比MyType
协议中设计的内容(即,目前什么都没有)。 根据您要通过扩展实现的目标,可以向MyType
添加蓝图,您可以通过UInt8
的实现(例如某些初始化程序)来实现这些UInt8
。 但是,更明智的方法是利用UInt8
符合有用的协议UnsignedInteger
, Equatable
和Comparable
的事实。 通过使用协议组合,扩展中的Element
:s可以方便地使用这些协议设计的所有方法,但是将这些元素的类型限制为符合您自己的协议MyType
(即,仅UInt8
):
protocol MyType {}
extension UInt8: MyType {}
extension Array where Element: MyType & UnsignedInteger {
mutating func superfluouslyReplaceAllElements(with value: Element) {
self = self.map { $0.advanced(by: $0.distance(to: value)) }
} /* using 'advanced(by:)' and 'distance(to:)' methods of
'Element', blueprinted in 'UnsignedInteger', to which
'Element' conforms */
mutating func elementsSquaredWithOverflow() -> Bool {
var overflow = false
self = self.map {
let result = Element.multiplyWithOverflow($0, $0)
overflow = overflow || result.overflow
return result.0
}
return overflow // did at least one element cause an arithmetic overflow?
}
}
var foo: [UInt8] = [14, 87, 13, 240]
print(foo.elementsSquaredWithOverflow()) // true (at least one arithmetic overflow)
print(foo) // [196, 145, 169, 0]
foo.superfluouslyReplaceAllElements(with: 42)
print(foo) // 42, 42, 42, 42
var bar: [UInt16] = [14, 87, 13, 240]
bar.superfluouslyReplaceAllElements(with: 42)
/* error: type 'UInt16' does not conform to protocol 'MyType'
OK, as expected! */
但是,这只是协议和类型约束的一小节课。 如果您打算在字节上下文中使用UInt8
序列,请在其对您的问题的评论中遵循@vadian:s的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.