Swift Literals

Swift Programming Language By Knownion

In most of the programming languages, literals and constants play a significant role in dealing with values within a program. Swift also support the concept of literals and constants. They are used to hold a constant value for expressing them within the code and hold a memory location. In this chapter, you will learn about how you can use constants and literals in the Swift programming language.

What are the Literals?

Literals are the most obvious kinds of constants and are used to express particular values within the source code of the program. In other words, it is the source code representation of a value. Here are the lists of some of the literals that are valid in Swift -


Swift Literals are of various types. They are:

Numeric Literals

It has its subcategories as integer and floating point literals and can be written as:

  • A decimal number, with no prefix
  • A binary number, with a 0b prefix
  • An octal number, with a 0o prefix
  • A hexadecimal number, with a 0x prefix

All the above literals have a decimal value of 17. It is to be noted that floating point literals can also be decimal with no prefix or hexadecimal literal with a 0x prefix. They must always have a number on both sides of the decimal point. They can also contain an optional exponent which is indicated by the upper case or lower case letter e and/or upper case or lower case letter p in case of hexadecimal floats.

For decimal numbers with an exponent of exp, the base number is multiplied by 10exp:

  • 1.25e2 means 1.25 × 102, or 125.0.
  • 1.25e-2 means 1.25 × 10-2, or 0.0125.

For hexadecimal numbers with an exponent of exp, the base number is multiplied by 2exp:

  • 0xFp2 means 15 × 22, or 60.0.
  • 0xFp-2 means 15 × 2-2, or 3.75.

String Literals

A string literal is a sequence of characters designated with a starting double quote (") and a closing double quote ("). It has the following form:


String literals cannot have un-escaped double quotes, and un-escaped backslash or carriage return. Special characters need to be used in string literals and form another branch of string literals known as an escape sequence, where each of the escape sequences has a special meaning. These are:

  • \0 : Null character
  • \\ : \character
  • \b : Backspace
  • \f : Form feed
  • \n : Newline
  • \r : Carriage return
  • \t : Horizontal tab
  • \v : Vertical tab
  • \' : Single Quote
  • \" : Double Quote
  • \000 : Octal number of one to three digits
  • \xhh... : Hexadecimal number of one or more digits


import Cocoa
let str = "Hello\tknownion\n\n\'Swift\'"


Hello knownion

Post a Comment