Last active
September 28, 2016 13:27
-
-
Save mono0926/580fd96b065d2cc771e7299547ed2ccb 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 String.CharacterView { | |
func read(_ i: Int) -> Character { | |
let index = self.index(startIndex, offsetBy: i) | |
return self[index] | |
} | |
func read(_ range: Range<Int>) -> String.CharacterView { | |
let start = self.index(startIndex, offsetBy: range.lowerBound) | |
let end = self.index(start, offsetBy: range.count) | |
return self[start..<end] | |
} | |
func read(_ range: ClosedRange<Int>) -> String.CharacterView { | |
let start = self.index(startIndex, offsetBy: range.lowerBound) | |
let end = self.index(start, offsetBy: range.count - 1) | |
return self[start...end] | |
} | |
} | |
let s = "12345" | |
s.characters.read(1) | |
// → 2 | |
String(s.characters.read(1..<3)) | |
// → 23 | |
String(s.characters.read(1...3)) | |
// → 234 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment