Swift – Character vs String

In Swift everything has a type. And these types can be fairly detailed. For example, Swift makes a clear distinction between a single Character, and a Collection of Characters.

Character

A Character in Swift can be any Character, this includes Emoji characters, and any other special character from any language set. You aren’t limited to UTF-8 characters.

Like many other programming languages Swift allows an escape sequence to represent special characters like these:

  • \n Line Feed
  • \r Carriage return
  • \t Tab stop
  • \\ Backslash

Characters also have a Name which describes the Character. For example a might be LATIN-SMALL LETTER A, while an Emoji might be FRONT-FACING BABY CHICK.

String

A String is a collection of Characters. The String has methods that allow us to access each Character in the String, and modify those Characters.

The String Class has so many options I couldn’t list them all here. All of the standard features you would expect exist. Though they might some different names. Things like:

  • substringFromIndex
  • substringToIndex
  • stringByReplacingCharactersInRange
  • stringByReplacingOccurrencesOfString

Leave a Reply

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