Skip to content

Instantly share code, notes, and snippets.

@powerje
Last active July 10, 2020 15:02
Show Gist options
  • Save powerje/d57f39bc36dd8efae1264c2b16c3997a to your computer and use it in GitHub Desktop.
Save powerje/d57f39bc36dd8efae1264c2b16c3997a to your computer and use it in GitHub Desktop.
peekCharacter using Scanner in Swift
extension Scanner {
var peekCharacter: Character? {
if isAtEnd { return nil }
return string[fallbackAwareCurrentIndex]
}
private var fallbackAwareCurrentIndex: String.Index {
get {
if #available(iOS 13, macCatalyst 13, macOS 10.15, *) {
return currentIndex
} else {
// https://github.com/apple/swift-corelibs-foundation/blob/2a5bc4d8a0b073532e60410682f5eb8f00144870/Sources/Foundation/ScannerAPI.swift#L25
let string = self.string
var index = string.toUTF16Index(scanLocation)
var delta = 0
while index != string.endIndex && index.samePosition(in: string) == nil {
delta += 1
index = string.toUTF16Index(scanLocation + delta)
}
return index
}
}
set {
if #available(iOS 13, macCatalyst 13, macOS 10.15, *) {
currentIndex = newValue
} else {
scanLocation = string.toUTF16Offset(newValue)
}
}
}
}
// https://fossies.org/linux/swift-swift/stdlib/public/core/StringBridge.swift
extension String {
func toUTF16Index(_ offset: Int) -> Index {
utf16.index(utf16.startIndex, offsetBy: offset)
}
func toUTF16Offset(_ idx: Index) -> Int {
utf16.distance(from: utf16.startIndex, to: idx)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment