Created
March 7, 2017 22:35
-
-
Save ruan65/9af95b919246fe1592e08ff16e6bfdbb to your computer and use it in GitHub Desktop.
swift better work with strings
This file contains hidden or 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) -> String? { | |
if characters.count > i && i >= 0 { | |
return String(Array(self.characters)[i]) | |
} | |
return nil | |
} | |
subscript (r: Range<Int>) -> String? { | |
guard r.lowerBound >= 0 && r.upperBound <= self.characters.count && r.upperBound >= r.lowerBound else { return nil } | |
let start = self.index(startIndex, offsetBy: r.lowerBound) | |
let end = self.index(startIndex, offsetBy: r.upperBound) | |
return self[Range(start ..< end)] | |
} | |
func indexAt(int: Int) -> String.Index? { | |
if characters.count > int { | |
return index(self.startIndex, offsetBy: int) | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment