Created
October 24, 2016 11:30
-
-
Save klein-artur/4c181073499b11d313fb02ce1318aa89 to your computer and use it in GitHub Desktop.
An extension of a string to provide subscription functionality.
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 { | |
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