Characters are numbers—an uppercase "A" is a different number than a lowercase "a." But in the alphabet, these letters are the same.
With lowercased and uppercased, we change the casing of characters. More advanced Foundation methods like capitalizedString
change just word-starting letters.
Here we introduce a string
containing the phrase "cat and dog." These are all lowercase letters and spaces. With uppercased()
we change all letters to uppercase.
Lowercased()
changes the letters back to their original case. Each method call creates a string
copy.let phrase = "cat and dog" // Get uppercase form of string. let upper = phrase.uppercased() print(upper) // Get lowercase form. let lower = upper.lowercased() print(lower)CAT AND DOG cat and dog
This method changes word-starting characters in a string
. It uppercases letters after spaces and other punctuation chars.
import Foundation // Use capitalized to uppercase the first letters. let phrase = "antarctica, asia, africa" let upperFirst = phrase.capitalized print(phrase) print(upperFirst) // Characters after punctuation are uppercased. let test = "ab,cd+ef-gh" let upperFirstTest = test.capitalized print(test) print(upperFirstTest)antarctica, asia, africa Antarctica, Asia, Africa ab,cd+ef-gh Ab,Cd+Ef-Gh
CaseInsensitiveCompare
When comparing strings, uppercase and lowercase letters are not usually equal. But with caseInsensitiveCompare
we can treat them as equal.
ComparisonResult.orderedSame
, we know the two strings are equal except for casing.import Foundation // These strings have different cases. let upper = "CAT" let lower = "cat" // Use caseInsensitiveCompare to compare the strings. let result = upper.caseInsensitiveCompare(lower) // If orderedSame the strings are equal except for case. if result == ComparisonResult.orderedSame { print("Strings have same order") }Strings have same order
It takes some CPU cycles to lowercase a string
. A dictionary lookup is typically faster. We can store the result of lowercased()
in a dictionary, and avoid repeat lookups.
var cache = [String: String]() func lowercasedCache(value: String) -> String { // Use the dictionary to avoid calling lowercased on a string 2 times. let result = cache[value] if result != nil { print("Cache used") return result! } // Store initial value in cache. let lower = value.lowercased() cache[value] = lower return lower } // Use our caching lowercase func. var test = "VALUE" print("Lower: " + lowercasedCache(value: test)) print("Lower: " + lowercasedCache(value: test))Lower: value Cache used Lower: value
Case is important: lowercase is not the same as uppercase. But sometimes we want (for display purposes) to capitalize or uppercase letters. And we can compare strings ignoring their cases.