Extension for the generic type `UnsafeMutablePointer <UInt8>`
I would like to create an extension for UnsafeMutablePointerthat only affects UnsafeMutablePointer<UInt8>...
I understand that these instructions are relevant, but I'm not sure how:
When extending a generic type, you do not provide a list of type parameters as part of the extension definition. Instead, a list of parameter types from the original type definition is available in the extension body, and the parameter type names of the original type are used to indicate type parameters from the original definition.
Basically, I am trying to use this method:
func toSwift(length: Int) -> [Int] {
var retVal : [Int] = []
for i in 0..<length {
retVal.append(Int(self[i]))
}
return retVal
}
act on selfwithout UnsafeMutablePointer<UInt8>as a parameter ... is this possible?
Swift 3.1
Swift 3.1 ( - Xcode 8.3), . :
extension UnsafeMutablePointer where Pointee == UInt8 {
func asArray(withLength length: Int) -> [Int] {
return UnsafeBufferPointer(start: self, count: length).map(Int.init)
}
}
Pre Swift 3.1
, . , "" UInt8, . , Int(...) _UInt8Type - .
protocol _UInt8Type {
func _asInt() -> Int
}
extension UInt8 : _UInt8Type {
func _asInt() -> Int {
return Int(self)
}
}
// Change 'Pointee' to 'Memory' for Swift 2
extension UnsafeMutablePointer where Pointee : _UInt8Type {
func asArray(withLength length:Int) -> [Int] {
return UnsafeBufferPointer(start: self, count: length).map{$0._asInt()}
}
}
, @AMomchilov . .
, (extension Type where Generic == SomeType) Swift Generics - , Swift.