Last active
February 9, 2016 18:50
-
-
Save freedom27/2858ff81ba8270c10ea4 to your computer and use it in GitHub Desktop.
Working with swift's Strings made easy
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 { | |
func substringWithRange(r: Range<Int>) -> String { | |
return substringWithRange(Range(start: startIndex.advancedBy(r.startIndex), end: startIndex.advancedBy(r.endIndex))) | |
} | |
func substringToIndex(i: Int) -> String { | |
return substringToIndex(startIndex.advancedBy(i)) | |
} | |
func substringFromIndex(i: Int) -> String { | |
return substringFromIndex(startIndex.advancedBy(i)) | |
} | |
func rangesForRegex(pattern: String) -> [Range<Int>] { | |
do { | |
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.UseUnixLineSeparators) | |
let matches = regex.matchesInString(self, options: NSMatchingOptions.ReportCompletion, range:NSRange(location: 0, length: self.characters.count)) | |
return matches.map{Range<Int>(start: $0.range.location, end: $0.range.location + $0.range.length)} | |
} catch { | |
print("An issue occurred while evaluating the regular expression") | |
return [Range<Int>]() | |
} | |
} | |
var trimmedString: String { | |
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) | |
} | |
var capitalizedFirstCharString: String { | |
return self[0..<1].uppercaseString + self[Range(start: startIndex.advancedBy(1), end: endIndex)] | |
} | |
// MARK: - subscripts | |
subscript (i: Int) -> Character { | |
return self[startIndex.advancedBy(i)] | |
} | |
subscript (i: Int) -> String { | |
return String(self[i] as Character) | |
} | |
subscript (r: Range<Int>) -> String { | |
return substringWithRange(r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment