Skip to content

Instantly share code, notes, and snippets.

@yossan
Created January 8, 2017 13:24
Show Gist options
  • Save yossan/4d9883d52fa2d3a5801a992cf4cc32f8 to your computer and use it in GitHub Desktop.
Save yossan/4d9883d52fa2d3a5801a992cf4cc32f8 to your computer and use it in GitHub Desktop.
Extension Data
import Foundation
extension Data {
func uint16() -> AnySequence<UInt16>? {
guard self.count % 2 == 0
else { return nil }
return AnySequence<UInt16> { () -> AnyIterator<UInt16> in
let size = self.count / 2
var currentIndex = 0
return AnyIterator<UInt16> {
self.withUnsafeBytes { (head: UnsafePointer<UInt16>) -> (UInt16?) in
guard currentIndex < size
else { return nil }
defer { currentIndex += 1 }
return head[currentIndex]
}
}
}
}
}
let data = "abcdefg".data(using: .utf16)!
data.uint16().flatMap {
for uint16 in $0 {
print(String(uint16, radix: 16))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment