Created
November 29, 2017 08:32
-
-
Save sgbasaraner/1faaf48418f0b8a127410ba9af1e0ad0 to your computer and use it in GitHub Desktop.
Title Case Extension for Swift 4
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
extension String { | |
func titlecased() -> String { | |
if self.count <= 1 { | |
return self.uppercased() | |
} | |
let regex = try! NSRegularExpression(pattern: "(?=\\S)[A-Z]", options: []) | |
let range = NSMakeRange(1, self.count - 1) | |
var titlecased = regex.stringByReplacingMatches(in: self, range: range, withTemplate: " $0") | |
for i in titlecased.indices { | |
if i == titlecased.startIndex || titlecased[titlecased.index(before: i)] == " " { | |
titlecased.replaceSubrange(i...i, with: String(titlecased[i]).uppercased()) | |
} | |
} | |
return titlecased | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @SunnyAstegic, which line do you get the crash from? Also, do you have an idea about the input?