Swift titleized String Extension


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:

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:

Leave a Reply

Your email address will not be published. Required fields are marked *