Swift Literals
A literal is a value written directly in source code whose type is obvious at a glance, such as 42, 3.14, "Runoob", and true.
Swift infers the type from the literal's form and context, so you usually don't need extra annotations when writing code.
What Is a Literal
In the three assignments below, the right-hand sides are all literals and the types of the left-hand variables are inferred automatically by Swift.
Example
let aNumber
=
3
// Inferred as Int
let aString
=
"Runoob"
// Inferred as String
let aBool
=
true
// Inferred as Bool
(
aNumber, aString, aBool
)
The execution result of the above program is:
3 Runoob true
If the context cannot infer the type, or you want a more precise type, you can write an explicit type annotation, such as let price: Double = 9.9.
Integer Literals
Integer literals can be written in decimal, binary, octal, or hexadecimal; the first three forms all yield the same Int value.
| Base | Prefix | Example | Decimal Value |
|---|---|---|---|
| Decimal | None | 17 |
17 |
| Binary | 0b |
0b10001 |
17 |
| Octal | 0o |
0o21 |
17 |
| Hexadecimal | 0x |
0x11 |
17 |
You can insert underscores _ inside numbers for readability; underscores are completely ignored and do not affect the value.
Example
let decimalInteger
=
17
// Decimal
let binaryInteger
=
0b10001
// Binary
let octalInteger
=
0o21
// Octal
let hexadecimalInteger
=
0x11
// Hexadecimal
(
decimalInteger, binaryInteger, octalInteger, hexadecimalInteger
)
// Underscores are only separators and are not part of the calculation
let oneMillion
=
1
_000_000
let cardNumber
=
1234
_5678_9012_3456
(
oneMillion, cardNumber
)
The execution result of the above program is:
17 17 17 17
1000000 1234567890123456
Note:A literal itself has no fixed bit width; the specific Int or Int8 type is determined by context. In the example above, with no type annotation, Swift infers it uniformly as Int。
Floating-Point Literals
A floating-point literal consists of an integer part, a decimal point, a fractional part, and an exponent part, with slightly more forms than integer literals.
Without an explicit annotation, floating-point literals default to Double (64-bit).
| Syntax | Example | Value | Description |
|---|---|---|---|
| Ordinary decimal | 12.1875 |
12.1875 | Most common |
| Decimal exponent | 1.21875e1 |
12.1875 | Multiply by 10 to the power of 1 |
| Hexadecimal | 0xC.3p0 |
12.1875 | (12 + 3/16) × 2⁰ |
| Hexadecimal exponent | 0x1p2 |
4.0 | 1 × 2² |
| Underscore separators | 1_000_000.000_000_1 |
1000000.0000001 | Only for readability |
The exponent part of a hexadecimal floating-point number uses the letter p (instead of e), meaning multiply by 2 to the power of.
Example
let decimalDouble
=
12.1875
// Ordinary decimal
let exponentDouble
=
1.21875e1
// 1.21875 × 10¹
let hexDouble
=
0x1p2
// 1 × 2² = 4.0
let hexDouble2
=
0xC.3p0
// (12 + 3/16) × 2⁰ = 12.1875
let readableDouble
=
1
_000_000.000_000_1
(
decimalDouble, exponentDouble, hexDouble, hexDouble2, readableDouble
)
The execution result of the above program is:
12.1875 12.1875 4.0 12.1875 1000000.0000001
For a negative number, just add a unary minus in front, such as -42.5, which is equivalent to negating the literal 42.5.
String Literals
A string literal is enclosed in a pair of double quotes and can contain ordinary characters, escape sequences, and interpolation expressions.
Example
let site
=
"www.runoob.com"
let greeting
=
"Hello, (site)"
// Backslash plus parentheses for string interpolation
(
greeting
)
The execution result of the above program is:
你好,www.runoob.com
Escape sequences
Swift supports only a few escape sequences, listed below; a mistake causes a compile-time error.
| Escape sequences | Meaning |
|---|---|
\0 |
Null character (null) |
\\ |
Backslash itself |
\t |
Horizontal tab |
\n |
Newline |
\r |
Carriage return |
\" |
Double quote |
\' |
Single quote |
\u{n} |
Unicode scalar,n with 1 to 8 hexadecimal digits |
Example
let stringL
=
"Hello\tWorld\nRunoob Tutorial:"http://www.runoob.com""
(
stringL
)
(
"Backslash: \ single quote: '"
)
let han
=
"\u{4E2D}"
(
"han = (han),count = (han.count)"
)
The execution result of the above program is:
Hello World
Runoob Tutorial:"http://www.runoob.com"
反斜线:\ 单引号:'
han = 中,count = 1
Note:Swift does not have C's \b、\f、\v, nor does it support octal escapes. Writing "\b" yields error: invalid escape sequence in literal。
Multiline Strings
A pair of triple quotes """ can be used to write a multiline string; the indentation of the closing triple quotes determines how much indentation is stripped from each line.
Example
let text
=
""
"
Runoob
www.runoob.com
"
""
(
text
)
(
"Length: (text.count)"
)
// In multiline strings you can write double quotes directly, no escaping needed
let quoted
=
""
"
He said: "
Welcome to Runoob
"
"
""
(
quoted
)
The execution result of the above program is:
Runoob
www.runoob.com
长度:21
他说:"欢迎来到 Runoob"
Raw strings
Adding a # outside the triple or double quotes gives a raw string: backslashes no longer trigger escapes, and \n is just two ordinary characters.
To do interpolation in a raw string, add a # after the backslash, written as #(...).
Example
// Backslashes are not escaped, \n is just two ordinary characters
let rawPath
=
#"Directory "C:\Users\Runoob" \n does not wrap"#
(
rawPath
)
// Interpolation in raw strings must be written as #(...)
let number
=
17
let rawInterp
=
#"Interpolation still works: #(number)"#
(
rawInterp
)
The execution result of the above program is:
目录 "C:\Users\Runoob" 里的 \n 不换行
插值仍然可用:17
Boolean literals
There are only two boolean literals: true and false, whose type is Bool.
Example
let isRunoob
=
true
let isClosed
=
false
(
isRunoob, isClosed
)
(
"The type of isRunoob is (type(of: isRunoob))"
)
The execution result of the above program is:
true false
isRunoob 的类型是 Bool
Note:nil is not a boolean literal; it means "no value" and can only be assigned to an optional type. Swift also has no implicit conversions such as "0 or empty string is false", so a condition must be a real Bool, see Part 9 for details:Swift Conditional Statements》。
Array and Dictionary Literals
An array literal lists elements in square brackets, while a dictionary literal lists key-value pairs in the form "key: value".
Example
let sites
:
[
String
]
=
[
"Runoob"
,
"RUNOOB"
,
"Runoob Tutorial"
]
(
sites
)
(
"Number of elements: (sites.count)"
)
let info
=
[
"name"
:
"Runoob"
,
"site"
:
"www.runoob.com"
]
(
info
[
"name"
]
!
, info
[
"site"
]
!
, info.
count
)
The execution result of the above program is:
["Runoob", "RUNOOB", "Runoob Tutorial"]
元素个数:3
Runoob www.runoob.com 2
Note:Dictionaries are unordered; iterating the same dictionary twice may print key-value pairs in different orders, so the code above uses specific keys to retrieve values instead of printing the whole dictionary directly.
Common questions
The following are the most common problems beginners encounter when writing literals.
| Problem | Description |
|---|---|
Why does a floating-point literal print as 4.0 |
Its type is Double, and it prints with a decimal point |
0b102 Does it compile? |
No, binary only allows 0 and 1 |
| Are underscores in a literal counted as part of the value? | No, underscores only serve as separators |
"\b" Why the error |
Swift has no such escape sequence; use \u{8} to represent a backspace character |
| Can a dictionary literal guarantee order? | No, dictionaries are inherently unordered |