Rails provides the titleize inflector (capitalizes all the words in a string), and I needed one for Swift too. The code snippet below adds a computed property to the String
class and follows these rules:
- The first letter of the first word of the string is capitalized
- The first letter of the remaining words in the string are capitalized, except those that are considered “small words”
Create a file in your Xcode project named String+Titleized.swift
and paste in the following String
extension:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import Foundation let SMALL_WORDS = ["a", "al", "y", "o", "la", "el", "las", "los", "de", "del"] extension String { var titleized:String { var words = self.lowercased().split(separator: " ").map({ String($0)}) words[0] = words[0].capitalized for i in 1..<words.count { if !SMALL_WORDS.contains(words[i]) { words[i] = words[i].capitalized } } return words.joined(separator: " ") } } |
Configure SMALL_WORDS
to your liking. In this example I was titleizing Spanish phrases, so my SMALL_WORDS
contains various definite articles and conjunctions. An example of the usage and output:
1 2 3 4 5 |
1> "CORUÑA y SAN ANTONIO".titleized $R0: String = "Coruña y San Antonio" 2> "el día de muertos".titleized $R1: String = "El Día de Muertos" |
Note: This post is a Swift 4.2 version of this one written in Swift 2.