Skip to content

Instantly share code, notes, and snippets.

@mfaani
Created December 1, 2024 20:16
Show Gist options
  • Save mfaani/14f5286131f2dcf4602e03cb1d1c020c to your computer and use it in GitHub Desktop.
Save mfaani/14f5286131f2dcf4602e03cb1d1c020c to your computer and use it in GitHub Desktop.
extension Character: Strideable {
public func distance(to other: Character) -> Int {
let selfValue = self.unicodeScalars.first?.value ?? 0
let otherValue = other.unicodeScalars.first?.value ?? 0
return Int(otherValue - selfValue)
}
public func advanced(by n: Int) -> Character {
guard let scalar = self.unicodeScalars.first else {
fatalError("Cannot advance an empty character")
}
guard self.unicodeScalars.count == 1 else {
fatalError("❌ Cannot advance when a character is made by combined code points. This is a limitation of Swift.")
}
let newValue = Int(scalar.value) + n
guard let newScalar = Unicode.Scalar(newValue) else {
fatalError("Resulting scalar value is invalid")
}
return Character(newScalar)
}
}
let a: Character = "a"
let z: Character = "z"
let alphabeticalRange = a...z
print(alphabeticalRange.count) // 26
for letter in alphabeticalRange {
print(letter) // prints a to z...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment