Skip to content

Instantly share code, notes, and snippets.

@klein-artur
Created October 24, 2016 11:30
Show Gist options
  • Save klein-artur/4c181073499b11d313fb02ce1318aa89 to your computer and use it in GitHub Desktop.
Save klein-artur/4c181073499b11d313fb02ce1318aa89 to your computer and use it in GitHub Desktop.
An extension of a string to provide subscription functionality.
extension String {
subscript (i: Int) -> Character {
get {
assert(i < self.characters.count && i >= 0, "Index out of range.")
return self[self.index(self.startIndex, offsetBy: String.IndexDistance(i))]
}
set {
assert(i < self.characters.count && i >= 0, "Index out of range.")
let index = self.index(self.startIndex, offsetBy: String.IndexDistance(i))
let endIndex = self.index(self.startIndex, offsetBy: String.IndexDistance(i+1))
let str = self.replacingCharacters(in: index..<endIndex, with: String(newValue))
self.characters = str.characters
}
}
subscript (i: UInt) -> Character {
get {
return self[Int(i)]
}
set {
self[Int(i)] = newValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment