Back to Blog

Swift: Capitalize and decapitalize a list

Sandy LaneSandy Lane

Video: Swift: Capitalize and decapitalize a list by Taught by Celeste AI - AI Coding Coach

Watch full page →

Swift: Capitalize and Decapitalize a List

In Swift, you can easily transform the capitalization of strings within a list using built-in methods. This example demonstrates how to capitalize the first letter of each string and how to convert all letters to lowercase, helping you manipulate text collections efficiently.

Code

let words = ["apple", "banana", "cherry"]

// Capitalize the first letter of each word
let capitalizedWords = words.map { $0.capitalized }

// Decapitalize each word (make all letters lowercase)
let decapitalizedWords = words.map { $0.lowercased() }

print("Capitalized:", capitalizedWords)   // ["Apple", "Banana", "Cherry"]
print("Decapitalized:", decapitalizedWords) // ["apple", "banana", "cherry"]

Key Points

  • Use the map function to apply transformations to every element in a list.
  • The capitalized property converts the first letter of a string to uppercase and the rest to lowercase.
  • The lowercased() method converts all characters in a string to lowercase.
  • These string methods help standardize text formatting in collections easily.