Last active
December 31, 2017 04:43
-
-
Save asmallteapot/6fcd3c1484943e6800ae690e6ad35fef to your computer and use it in GitHub Desktop.
Fix arbitrary input strings into camelCasedWords [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
import Foundation | |
let sampleInputs = [ | |
"OAuth Token", | |
"Hello-World!", | |
] | |
extension String { | |
func capitalized() -> String { | |
guard let firstCharacter = self.characters.first else { return "" } | |
return self.replacingCharacters(in: (self.startIndex)...(self.startIndex), with: String(firstCharacter).uppercased()) | |
} | |
} | |
func fix(_ input: String) -> String { | |
let words = input.split(whereSeparator: { character in | |
return character == " " || character == "-" | |
}) | |
var shouldCapitalizeNextWord: Bool = false | |
let output = words.reduce("") { (output, word) -> String in | |
let fixedWord = word.lowercased().trimmingCharacters(in: .punctuationCharacters) | |
if shouldCapitalizeNextWord { | |
return output.appending(fixedWord.capitalized()) | |
} else { | |
shouldCapitalizeNextWord = true | |
return output.appending(fixedWord) | |
} | |
} | |
return output | |
} | |
let fixed = sampleInputs.map { fix($0) } | |
// [ "oauthToken", "helloWorld"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment