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
}
}
@SunnyAstegic
Copy link

Getting a rare crash while using above code

Crashed: com.apple.main-thread
0 libswiftCore.dylib 0x203b00 specialized fatalErrorMessage(:_:file:line🎏) + 296
1 libswiftCore.dylib 0x20910c specialized BidirectionalCollection._distance(from:to:) + 732
2 libswiftCore.dylib 0x21fca0 specialized copyCollectionToContiguousArray(:) + 64
3 libswiftCore.dylib 0x24dbf8 specialized String.uppercased() + 1028
4 appName 0x7dcaa4 String.titlecased() + 65 (StrExtension.swift:65)

@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