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
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)