Skip to content

Instantly share code, notes, and snippets.

@sgbasaraner
Created November 29, 2017 08:32
Show Gist options
  • Save sgbasaraner/1faaf48418f0b8a127410ba9af1e0ad0 to your computer and use it in GitHub Desktop.
Save sgbasaraner/1faaf48418f0b8a127410ba9af1e0ad0 to your computer and use it in GitHub Desktop.
Title Case Extension for Swift 4
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
}
}
@sgbasaraner
Copy link
Author

Hi @SunnyAstegic, which line do you get the crash from? Also, do you have an idea about the input?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment