Last active
March 10, 2016 03:36
-
-
Save chuthan20/2c05e342b41c18c3a39f to your computer and use it in GitHub Desktop.
Swift string extensions
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
import Foundation | |
extension String { | |
subscript(range: NSRange) -> String { | |
get { | |
let comp = self | |
let begin = comp.startIndex.advancedBy(range.location) | |
let sre = comp.substringWithRange(begin ..< begin.advancedBy(range.length)) | |
return sre | |
} | |
} | |
/* starts to end -- end can be <= 0 */ | |
subscript(start:Int, var end:Int) -> String { | |
get { | |
let comp = self | |
return comp.substringWithRange(self.startIndex.advancedBy(start) ..< self.endIndex.advancedBy(end)) | |
} | |
} | |
var fullRange: Range<String.Index> { | |
return self.startIndex ..< self.endIndex | |
} | |
var fullNSRange: NSRange { | |
return NSRange(location: 0, length: self.characters.count) | |
} | |
} | |
// usage | |
let str = ">Hello, World<" | |
print(str[0, 0]) | |
print(str[1, -1]) | |
print(str[NSRange.init(location: 1, length: 4)]) | |
print(str.fullRange) | |
print(str.fullNSRange) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment