Skip to content

Instantly share code, notes, and snippets.

@mono0926
Last active September 28, 2016 13:27
Show Gist options
  • Save mono0926/580fd96b065d2cc771e7299547ed2ccb to your computer and use it in GitHub Desktop.
Save mono0926/580fd96b065d2cc771e7299547ed2ccb to your computer and use it in GitHub Desktop.
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