Created
December 1, 2024 20:16
-
-
Save mfaani/14f5286131f2dcf4602e03cb1d1c020c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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