extension String {
func firstCharacterUpperCase() -> String? {
let lowercaseString = self.lowercaseString
return lowercaseString.stringByReplacingCharactersInRange(lowercaseString.startIndex...lowercaseString.startIndex, withString: String(lowercaseString[lowercaseString.startIndex]).uppercaseString)
}
}
let x = "heLLo"
let m = x.firstCharacterUpperCase()
Swift 5の場合:
extension String {
func firstCharacterUpperCase() -> String? {
guard !isEmpty else { return nil }
let lowerCasedString = self.lowercased()
return lowerCasedString.replacingCharacters(in: lowerCasedString.startIndex...lowerCasedString.startIndex, with: String(lowerCasedString[lowerCasedString.startIndex]).uppercased())
}
}
.capitalizedString
Xcode 7 Beta 4では動作しないことに注意してください。Swift2.0では文字列が少し変更されています。