Overview literals in Swift
numeric literals
Integer literals 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
let decimalInteger = 17
let binaryInteger = 0b10001 // 17 in binary notation
let octalInteger = 0o21 // 17 in octal notation
let hexadecimalInteger = 0x11 // 17 in hexadecimal notation
Floating-point literals can be decimal (with no prefix), or hexadecimal (with a 0x prefix). They must always have a number (or hexadecimal number) on both sides of the decimal point.
Decimal floats can also have an optional exponent, indicated by an uppercase or lowercase e; hexadecimal floats must have an exponent, indicated by an uppercase or lowercase p.
let decimalDouble = 12.1875
let exponentDouble = 1.21875e1
let hexadecimalDouble = 0xC.3p0
Both integers and floats can be padded with extra zeros and can contain underscores to help with readability.
let paddedDouble = 000123.456
let oneMillion = 1_000_000
let justOverOneMillion = 1_000_000.000_000_1
string literals
A string literal is a sequence of characters in double quotes. May contain any Unicode (UTF-16) characters. If your editor and file system allow it, you can use such characters directly in your code. If not, you can use a "Unicode escape": \u{n}, where n is a 1–8 digit hexadecimal number.
You can escape special characters \0 (null character), \\ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quotation mark) and \' (single quotation mark)
let hello = "Hello"
let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
// "Imagination is more important than knowledge" - Einstein
let dollarSign = "\u{24}" // $, Unicode scalar U+0024
let blackHeart = "\u{2665}" // ♥, Unicode scalar U+2665
let sparklingHeart = "\u{1F496}" // 💖, Unicode scalar U+1F496
Swift support string templates
// \(some_swift_code)
let num = 64
print("we have number \(num)")
Swift support multiline string literals, that is a sequence of characters surrounded by three double quotation marks.
If you want to use line breaks to make your source code easier to read, but you don’t want the line breaks to be part of the string’s value, write a backslash (\) at the end of those lines.
let quotation = """
The White Rabbit put on his spectacles. "Where shall I begin, \
please your Majesty?" he asked.
"Begin at the beginning," the King said gravely, "and go on
till you come to the end; then stop."
"""
A multiline string can be indented to match the surrounding code. The whitespace before the closing quotation marks (""") tells Swift what whitespace to ignore before all of the other lines. However, if you write whitespace at the beginning of a line in addition to what’s before the closing quotation marks, that whitespace is included.
let str = """
first line
second line, underline spaces will be included
third line
"""
array literals
Array literal allows to write one or more values as an array collection. An array literal is written as a list of values, separated by commas, surrounded by a pair of square brackets:
// [value_1, value_2, value_3, ... value_n]
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items
You can use array literal to set value to the Set.
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
dictionary (map) literals
Dictionary literal allows to write one or more key-value pairs as a Dictionary collection.
A key-value pair is a combination of a key and a value. In a dictionary literal, the key and value in each key-value pair are separated by a colon. The key-value pairs are written as a list, separated by commas, surrounded by a pair of square brackets:
// [key 1: value 1, key 2: value 2, key 3: value 3]
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
tuple literals
A tuple literal is written as a list of values, separated by commas, surrounded by a pair of round brackets.
You can name the individual elements in a tuple when the tuple is defined.
You can access to the tuple values by name or index.
let http404Error = (404, "Not Found")
let http200Status = (statusCode: 200, description: "OK")
print("The status code is \(http404Error.0)")
// Prints "The status code is 404"
print("The status message is \(http404Error.1)")
// Prints "The status message is Not Found"
print("The status code is \(http200Status.statusCode)")
// Prints "The status code is 200"
print("The status message is \(http200Status.description)")
// Prints "The status message is OK"