Editor’s Note: This code is compatible with Swift 2.0 and has not been tested on previous versions of the language!
Rails provides the titleize inflector, 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:
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.lowercaseString.characters.split(" ").map { String($0) } words[0] = words[0].capitalizedString for i in 1..<words.count { if !SMALL_WORDS.contains(words[i]) { words[i] = words[i].capitalizedString } } return words.joinWithSeparator(" ") } } |
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" |