I would like to split the CamelCase line into space-separated words in a new line. Here is what I still have:
var camelCaps: String {
guard self.count > 0 else { return self }
var newString: String = ""
let uppercase = CharacterSet.uppercaseLetters
let first = self.unicodeScalars.first!
newString.append(Character(first))
for scalar in self.unicodeScalars.dropFirst() {
if uppercase.contains(scalar) {
newString.append(" ")
}
let character = Character(scalar)
newString.append(character)
}
return newString
}
let aCamelCaps = "aCamelCaps"
let camelCapped = aCamelCaps.camelCaps
let anotherCamelCaps = "ÄnotherCamelCaps"
let anotherCamelCapped = anotherCamelCaps.camelCaps
I am inclined to suspect that perhaps this is not the most efficient way of converting into space-separated words if I call it in a narrow loop, or 1000 times. Are there any more efficient ways to do this in Swift?
[Edit 1:] The solution I need should remain common for Unicode scalars, and not just for Roman ASCII "A..Z".
[Edit 2:] The decision should also omit the first letter, that is, Do not put a space before the first letter.
[Edit 3:] Updated Swift 4 syntax and added uppercaseLetters caching, which improves performance in very long lines and narrow loops.