Created
January 8, 2017 13:24
-
-
Save yossan/4d9883d52fa2d3a5801a992cf4cc32f8 to your computer and use it in GitHub Desktop.
Extension Data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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