Created
October 30, 2017 23:24
-
-
Save khanlou/284dc5facad870a0b986511909c10261 to your computer and use it in GitHub Desktop.
This file contains 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 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) }) |
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"?
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
Does it matter that line 12 can return a negative value? Seems like distance should be positive