Skip to content

Instantly share code, notes, and snippets.

@NSExceptional
Created March 4, 2019 04:48
Show Gist options
  • Save NSExceptional/82635799aa6bf08ec893854544f4cf5a to your computer and use it in GitHub Desktop.
Save NSExceptional/82635799aa6bf08ec893854544f4cf5a to your computer and use it in GitHub Desktop.
Sensible Swift snippets
extension String {
var length: Int {
return self.lengthOfBytes(using: .utf8)
}
subscript(index: String.Index) -> Character {
get { return self.characters[index] }
set {
self.remove(at: index)
self.insert(newValue, at: index)
}
}
subscript(range: Range<Index>) -> String {
get { return String(self[range]) }
set { self.replaceSubrange(range, with: newValue) }
}
func getIndex(_ v: Int) -> Index {
return self.index(startIndex, offsetBy: v)
}
func getIndexRange(_ r: CountableRange<Int>) -> Range<Index> {
let start = getIndex(r.lowerBound)
let end = index(start, offsetBy: r.count)
return start..<end
}
subscript(index: Int) -> Character {
get { return self[getIndex(index)] }
set { self[getIndex(index)] = newValue }
}
subscript(range: CountableRange<Int>) -> String {
get { return self[getIndexRange(range)] }
set { self[getIndexRange(range)] = newValue }
}
subscript(range: NSRange) -> String {
get { return self[CountableRange<Int>(range)!] }
set { self[CountableRange<Int>(range)!] = newValue }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment