Swift Literals

A Literal is the direct value of variable or constant. It may be a number, character or string. Literals are used to initialize or assign value to variables or constants.

Example:

Here, javatpoint.com is a literal and siteName is a constant.

Types of Swift Literals

Integer Literals

  • Binary Literals
    • It is used to represent binary values.
    • It begins with 0b.
  • Octal Literals
    • It is used to represent octal values.
    • It begins with 0o.
  • Hexadecimal Literals
    • It is used to represent hexadecimal value.
    • It begins with 0x.
  • Decimal Literals
    • It is used represent decimal value.
    • It begins with nothing. Everything you declare in integer literal is of type decimal.

Example of Integer Literal:

Output:

255
1231

The above example contains two integer literals 0b11111111 (binary literal) and 1231 (decimal literal). 255 is the decimal value of 11111111 that's why the print(binaryNumber) statement outputs 255 in the screen.

String & Character Swift literals

A sequence of characters covered by double quotes is called string literal and a single character covered by double quotes is called character literal.

Example:

Output:

C
C is an awesome programming language

Floating Point Literals

Floating point literals are used for float and double values. There are two types of floating point literals:

Decimal:

It can store an optional exponent, indicated by an uppercase or lowercase e. For decimal numbers with an exponent of exp, the base number is multiplied by 10exp.

Example:

Output:

3.1416
314.0

Hexadecimal:

Hexadecimal floats must contain an exponent, indicated by an uppercase or lowercase p. For hexadecimal numbers with an exponent of exp, the base number is multiplied by 2exp.

Example:

Output:

15360.0
0.003662109375

Boolean Literals

There are two Boolean literals in Swift: true and false.

Example:

Output:

false
true

Type Alias

The typealias is used to create a new name for an existing type.

Syntax:

Example:

Let's take an example where we put "Raj" as another name for type Int.

Output:

100

Type Safety

Swift 4 is a type-safe language. If your code requires Int, then you can't use String. It performs type-checks when compiling your code and flags any mismatched types as errors.

Example:

Output:

main.swift:2:8: error: cannot assign value of type 'String' to type 'Int'
varA = "Hello World!"
       ^~~~~~~~~~~~~~

You can see that the above program get a compile time error just because of type safety.

Type Inference

Swift is a type inference language means when you compile the Swift code, it automatically check the type of value you provide. It automatically choose the appropriate data type for successful execution.

Example:

Output:

Love is life
143
3.1416
3.1416