Skip to content

Instantly share code, notes, and snippets.

@ctreffs
Last active August 24, 2020 19:09
Show Gist options
  • Save ctreffs/c167337bc2661f6fa386d935b27902f3 to your computer and use it in GitHub Desktop.
Save ctreffs/c167337bc2661f6fa386d935b27902f3 to your computer and use it in GitHub Desktop.
Generate the alphabet quickly [Swift]
let asciiChars = Character("A")...Character("z")
let allCharsAsString = String(asciiChars)
extension Character: Strideable {
public func distance(to other: Character) -> Int {
guard let value = self.asciiValue, let otherValue = other.asciiValue else {
fatalError("ASCII values are nil")
}
return abs(Int(value) - Int(otherValue))
}
public func advanced(by n: Int) -> Character {
guard let value = self.asciiValue else {
fatalError("Could not get ASCII value")
}
return Character(UnicodeScalar(value + UInt8(truncatingIfNeeded: n)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment