Created
March 19, 2016 10:49
-
-
Save niftycode/b6ae63c6303ed3cd8cc1 to your computer and use it in GitHub Desktop.
Useful String extensions
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 { | |
// string length | |
var len: Int { | |
return self.characters.count | |
} | |
// retrieve a single character | |
subscript(n: Int) -> Character { | |
if n < 0 || n > self.len { | |
return " " | |
} else { | |
let index = startIndex.advancedBy(n) | |
return self[index] | |
} | |
} | |
// retrieve a substring using an integer range | |
subscript(r: Range<Int>) -> String { | |
let start = startIndex.advancedBy(r.startIndex) | |
let end = startIndex.advancedBy(r.endIndex) | |
let range = start..<end | |
return self[range] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment