Created
April 12, 2016 01:28
-
-
Save cyrilis/9c7e5364042a6bed1a20f9c610154acb to your computer and use it in GitHub Desktop.
Swift String substring
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 (r: Range<Int>) -> String { | |
get { | |
let startIndex = self.startIndex.advancedBy(r.startIndex) | |
let endIndex = startIndex.advancedBy(r.endIndex - r.startIndex) | |
return self[Range(start: startIndex, end: endIndex)] | |
} | |
} | |
func substring(from: Int) -> String { | |
let end = self.characters.count | |
return self[from..<end] | |
} | |
func substring(from: Int, length: Int) -> String { | |
let end = from + length | |
return self[from..<end] | |
} | |
} | |
var s = "Hello, playground" | |
s[0...5] | |
s[0..<5] | |
s.substring(5) | |
s.substring(0,length: 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment