Skip to content

Instantly share code, notes, and snippets.

@khanlou
Created October 30, 2017 23:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khanlou/284dc5facad870a0b986511909c10261 to your computer and use it in GitHub Desktop.
Save khanlou/284dc5facad870a0b986511909c10261 to your computer and use it in GitHub Desktop.
extension Character: Strideable {
public typealias Stride = Int
public func distance(to other: Character) -> Character.Stride {
guard let first = self.unicodeScalars.first else {
fatalError()
}
guard let other = other.unicodeScalars.first else {
fatalError()
}
return (Int(first.value) - Int(other.value))
}
public func advanced(by n: Character.Stride) -> Character {
guard let first = self.unicodeScalars.first else {
fatalError()
}
guard let scalar = UnicodeScalar(Int(first.value) + n) else {
fatalError()
}
return Character(scalar)
}
}
("A" as Character ... "Z").forEach({ print($0) })
@freddy1h
Copy link

freddy1h commented Jun 9, 2022

Does it matter that line 12 can return a negative value? Seems like distance should be positive

@khanlou
Copy link
Author

khanlou commented Jun 9, 2022

Not exactly. If it couldn't be negative, then given the character "d" and a distance of 1, how would it know whether to go to "c" or "e"?

@freddy1h
Copy link

freddy1h commented Jun 9, 2022

Ok thank you, that makes sense. ("d" as Character).advanced(by: 1) goes to "e" and then passing -1 will go to "c"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment