Skip to content

Instantly share code, notes, and snippets.

@yossan
Created January 5, 2017 14:55
Show Gist options
  • Save yossan/00274a4a43acfc820c2cd41390639534 to your computer and use it in GitHub Desktop.
Save yossan/00274a4a43acfc820c2cd41390639534 to your computer and use it in GitHub Desktop.
Data
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