Skip to content

Instantly share code, notes, and snippets.

@niftycode
Created March 19, 2016 10:49
Show Gist options
  • Save niftycode/b6ae63c6303ed3cd8cc1 to your computer and use it in GitHub Desktop.
Save niftycode/b6ae63c6303ed3cd8cc1 to your computer and use it in GitHub Desktop.
Useful String extensions
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