Created
March 4, 2019 04:48
-
-
Save NSExceptional/82635799aa6bf08ec893854544f4cf5a to your computer and use it in GitHub Desktop.
Sensible Swift snippets
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 { | |
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