Created
January 5, 2017 15:10
-
-
Save yossan/b6b60aa948d65b8190f02fd74db8090d to your computer and use it in GitHub Desktop.
UInt16Sequence
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 | |
struct UInt16Sequence: Sequence, IteratorProtocol { | |
var data: Data | |
init?(data: Data) { | |
guard data.count % 2 == 0 | |
else { return nil } | |
self.data = data | |
} | |
var currentIndex: Int = 0 | |
mutating func next() -> UInt16? { | |
return self.data.withUnsafeBytes { (uint16Pointer: UnsafePointer<UInt16>) -> (UInt16?) in | |
guard self.currentIndex < data.count / 2 | |
else { return nil } | |
defer { self.currentIndex += 1 } | |
return uint16Pointer[self.currentIndex] | |
} | |
} | |
} | |
let data = "a".data(using: .utf16)! | |
let uint16sequ = UInt16Sequence(data: data)! | |
for uint16 in uint16sequ { | |
print(String(uint16, radix: 16, uppercase: false)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment