Skip to content

Instantly share code, notes, and snippets.

@mono0926
Last active October 1, 2016 01:57
Show Gist options
  • Save mono0926/29db2430c27b77cf4b2fa7ce7b448e64 to your computer and use it in GitHub Desktop.
Save mono0926/29db2430c27b77cf4b2fa7ce7b448e64 to your computer and use it in GitHub Desktop.
// まずString.CharacterViewにメソッド定義
extension String.CharacterView {
public subscript(sequentialAccess range: Range<Int>) -> String.CharacterView {
let lower = range.lowerBound
let startIndex = index(self.startIndex, offsetBy: lower)
let endIndex = index(startIndex, offsetBy: range.count)
return self[startIndex..<endIndex]
}
public subscript(sequentialAccess index: Int) -> Character {
return self[sequentialAccess: index..<index + 1].first!
}
}
// Stringにはラップメソッドを生やす
extension String {
public subscript(sequentialAccess range: Range<Int>) -> String {
return String(characters[sequentialAccess: range])
}
public subscript(sequentialAccess index: Int) -> String {
return self[sequentialAccess: index..<index + 1]
}
}
let s = "Café du 🌍"
s[sequentialAccess: 2..<4] // fé
s[sequentialAccess: 3] // é
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment