String.uppercased() / lowercased() / capitalized
In Swift, you can convert a string to uppercase with uppercased(), to lowercase with lowercased(), and capitalize the first letter of each word with capitalized.
Syntax
// Convert to uppercase string.uppercased() // Convert to lowercase string.lowercased() // Capitalize the first letter of each word string.capitalized // Locale-aware conversions string.localizedUppercase string.localizedLowercase string.localizedCapitalized
Methods and Properties
| Method / Property | Description |
|---|---|
| string.uppercased() | Returns a new string with all characters converted to uppercase. |
| string.lowercased() | Returns a new string with all characters converted to lowercase. |
| string.capitalized | Returns a string with the first letter of each word uppercased and the rest lowercased. |
| string.localizedUppercase | Converts to uppercase based on the current locale. |
| string.localizedLowercase | Converts to lowercase based on the current locale. |
| string.localizedCapitalized | Capitalizes the first letter of each word based on the current locale. |
| string.uppercased(with: locale) | Converts to uppercase using the specified locale. |
Sample Code
// Uppercase and lowercase conversion
let text = "Hello, Swift World!"
print(text.uppercased()) // HELLO, SWIFT WORLD!
print(text.lowercased()) // hello, swift world!
print(text.capitalized) // Hello, Swift World!
// Use case: case-insensitive comparison
let input = "swift"
let keyword = "Swift"
if input.lowercased() == keyword.lowercased() {
print("Match found (case-insensitive)")
}
// Normalize a file extension
let filename = "Photo.JPG"
let ext = (filename as NSString).pathExtension.lowercased()
if ext == "jpg" || ext == "jpeg" {
print("JPEG image: \(filename)")
}
// Normalize user input
let userInput = " TOKYO "
let normalized = userInput.trimmingCharacters(in: .whitespaces).lowercased()
print(normalized) // tokyo
// Convert to title case
let title = "the quick brown fox"
print(title.capitalized) // The Quick Brown Fox
// Locale-aware conversion
import Foundation
let turkishText = "istanbul"
print(turkishText.localizedUppercase) // Result varies by locale (e.g., İSTANBUL in tr_TR)
Notes
uppercased() and lowercased() fully support Unicode. Since they are locale-independent, they are safe to use in most situations.
For case-insensitive comparisons, either call lowercased() on both sides before comparing, or use localizedStandardContains. Some languages, such as Turkish, have different casing rules (e.g., i → İ). Use localizedUppercase when your app needs to support multiple languages.
For string replacement and trimming, see string.replacingOccurrences() / trimmingCharacters().
If you find any errors or copyright issues, please contact us.