Created
January 5, 2017 14:55
-
-
Save yossan/00274a4a43acfc820c2cd41390639534 to your computer and use it in GitHub Desktop.
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 | |
struct Data16: Sequence, IteratorProtocol { | |
let data8: Data | |
init(_ data8: Data) { | |
self.data8 = data8 | |
self.currentIndex = 0 | |
} | |
var currentIndex: Int | |
mutating func next() -> UInt16? { | |
return data8.withUnsafeBytes { (utf16Pointer: UnsafePointer<UInt16>) -> (UInt16?) in | |
guard self.currentIndex < (self.data8.count) / 2 | |
else { return nil } | |
defer { self.currentIndex += 1 } | |
return utf16Pointer[self.currentIndex] | |
} | |
} | |
} | |
let str = "あ" | |
let data16 = Data16(str.data(using: .utf16)!) | |
for d in data16 { | |
print("type(of: d) = \(type(of: d))") | |
print(d) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment