Swift Data Types
Swift is a strongly typed language: every value has a definite type, which determines what it can store and what operations it supports.
This chapter reviews Swift's basic data types in the order "numbers → text → tuples → collections → special types."
Arrays, dictionaries, and sets are only surveyed here; their detailed usage is covered in dedicated chapters later.
https://www.runoob.com/wp-content/uploads/2015/10/05-type-system.svg
Integer type
Swift's integers come in signed and unsigned varieties, each with different bit widths.
The most commonly used is Int, whose bit width follows the platform; on 64-bit devices it's equivalent to Int64.
Example
// The bit width of Int depends on the platform: Int64 on 64-bit platforms
(
"Int max: (Int.max)"
)
(
"Int min: (Int.min)"
)
// Fixed-width integer types
(
"Int8 range: (Int8.min) ~ (Int8.max)"
)
(
"UInt8 range: (UInt8.min) ~ (UInt8.max)"
)
(
"Int64 max: (Int64.max)"
)
Running result:
Int 最大值:9223372036854775807
Int 最小值:-9223372036854775808
Int8 范围:-128 ~ 127
UInt8 范围:0 ~ 255
Int64 最大值:9223372036854775807
Every integer type has two static properties, .min and .max; just read them to get the boundary values—don't hardcode these numbers.
| Type | Bit width | Value range |
|---|---|---|
| Int8 | 8 bits | -128 ~ 127 |
| UInt8 | 8 bits | 0 ~ 255 |
| Int16 | 16-bit | -32768 ~ 32767 |
| Int32 | 32-bit | -2147483648 ~ 2147483647 |
| Int64 | 64-bit | -9223372036854775808 ~ 9223372036854775807 |
| UInt | Follows the platform | 0 ~ largest unsigned integer on the platform |
Unless you truly need a specific bit width, use Int throughout so your code works correctly on both 32-bit and 64-bit platforms.
Integer overflow terminates the program by default rather than silently wrapping around as in C, which avoids many hidden bugs.
Note:If you really need wraparound on overflow, use the overflow operators &+、&-、&*; ordinary operators + trap on overflow.
Floating-point types
Swift provides two floating-point types: Double for double precision and Float for single precision.
Without a type annotation, literals with a decimal point are always inferred as Double.
Example
// Use built-in properties to view floating-point bounds; don't hardcode numbers
(
"Double max: (Double.greatestFiniteMagnitude)"
)
(
"Double smallest positive: (Double.leastNonzeroMagnitude)"
)
(
"Float max: (Float.greatestFiniteMagnitude)"
)
(
"Double significand: (Double.significandBitCount) binary digits"
)
Running result:
Double 最大值:1.7976931348623157e+308
Double 最小正数:5e-324
Float 最大值:3.4028235e+38
Double 有效位数:52 位二进制
| Type | Precision | Typical scenario |
|---|---|---|
| Double | About 15 significant decimal digits | The default choice for the vast majority of computations |
| Float | About 6 significant decimal digits | Memory-sensitive graphics data with low precision requirements |
Never compare floating-point numbers directly with ==, because binary can't represent decimals like 0.1 exactly; instead compare whether the absolute difference is below some tolerance.
Note:Floating-point bounds should be obtained with .greatestFiniteMagnitude、.leastNonzeroMagnitude such built-in properties; don't hardcode 1.7976931348623157e+308 numbers like that, which are error-prone and hard to read.
Boolean type
Swift's only Boolean type is Bool, with just two values: true and false.
This differs from other languages: nil isn't a Boolean, and the integer 0 can't be used as one either.
Example
let isOpen
=
true
// Bool: only true and false
let grade
:
Character
=
"A"
// Character: a single character
let site
:
String
=
"RUNOOB"
(
isOpen
)
(
grade
)
(
site
)
(
type
(
of
:
isOpen
)
)
(
type
(
of
:
grade
)
, type
(
of
:
site
)
)
Running result:
true
A
RUNOOB
Bool
Character String
All conditional expressions must be of type Bool; if count or if optionalValue are invalid.
Boolean literals have only two values, no third; use isEmpty to test emptiness and optional binding to test whether an optional has a value.
Characters and strings
Character represents a single character and String a sequence of characters; the two can be converted into each other.
Swift characters are based on "extended grapheme clusters," so a single emoji or an accented letter counts as one Character.
Example
// A string literal can be converted to Character, provided it contains exactly one character
let letter
=
Character
(
"S"
)
(
letter, type
(
of
:
letter
)
)
// String can be concatenated directly with a Character
var site
=
"www.runoob"
site.
append
(
"."
)
site.
append
(
contentsOf
:
"com"
)
(
site
)
Running result:
S Character
www.runoob.com
When converting with Character("S"), if the string contains multiple characters the program terminates at runtime, so this initializer suits only cases where the length is definitely 1.
A string's index isn't an integer but a String.Index, because different characters may occupy different numbers of bytes—covered in detail in article 8.
Tuple
A tuple combines multiple values of different types into one whole, suiting the temporary case of returning several results.
Tuple elements can be nameless and accessed by index, or named and accessed by name.
Example
// Define a tuple
let site
=
(
"RUNOOB"
,
"www.runoob.com"
)
// Access by index
(
site.0, site.1
)
// Name the elements
let course
=
(
name
:
"Swift Tutorial"
, chapters
:
43
)
(
course.
name
)
(
course.
chapters
)
// Destructure into separate constants
let
(
name, url
)
=
site
(
name, url
)
Running result:
RUNOOB www.runoob.com
Swift 教程
43
RUNOOB www.runoob.com
Tuples suit temporary cases like a function returning multiple values; if the combination is reused or needs attached methods, define a struct.
A tuple can't conform to protocols or have methods added—its biggest difference from a struct.
Overview of collection types
The Swift standard library provides three collection types: arrays, dictionaries, and sets.
All are value types and are copied on assignment or when passed as arguments; the details are explained in article 32 on copy-on-write.
Example
import Foundation
// Array: ordered, elements of the same type
var langs
=
[
"Swift"
,
"Objective-C"
,
"C"
]
// Dictionary: key-value pairs, unordered
var sites
=
[
"name"
:
"RUNOOB"
,
"url"
:
"www.runoob.com"
]
// Set: unordered with unique elements
var letters
:
Set
<
Character
=
[
"a"
,
"b"
,
"c"
,
"a"
]
print
(langs.
count
, langs
[
0
]
)
(
sites
[
"name"
]
??
"File %s type is: %s%n"
)
(
letters.
count
)
(
letters.
sorted
(
)
)
Running result:
3 Swift
RUNOOB
3
["a", "b", "c"]
| Type | Is it ordered | Are elements unique | Access Method |
|---|---|---|---|
| Array | Ordered | Duplicates allowed | Integer index |
| Dictionary | Unordered | Keys unique, values may repeat | Key |
| Set | Unordered | the only | Membership testing |
Note that two "a" values were written when creating the set above, but only one remains—this is automatic deduplication by the set.
Dictionary iteration order isn't guaranteed; sort first when a stable order is needed, as highlighted in article 13.
Overview of optionals
The Optional type means "there may or may not be a value," marked with a question mark ?.
It's the core of Swift's null safety; nearly every operation that can fail returns an optional.
Example
// Optional: a value may be present or may be nil
var nickname
:
String
?
=
nil
(
nickname
??
"No nickname"
)
nickname
=
"Runoob"
if
let name
=
nickname
{
(
"Nickname is (name)"
)
}
Running result:
没有昵称
昵称是 Runoob
?? is the nil-coalescing operator; when the left side is nil, it takes the default value on the right.
The full use of optionals—including forced unwrapping, optional binding, and optional chaining—is covered in detail in articles 29 and 30.
Note:An optional can't be used directly in operations or as a Boolean; it must be unwrapped first. This is an important difference between Swift and Objective-C.
Any, AnyObject, and Never
Besides concrete types, Swift has several special types representing "any type."
Any can represent a value of any type, including value types, reference types, and function types.
Example
// Any can represent a value of any type
var items
:
[
Any
]
=
[
"RUNOOB"
,
43
,
true
,
9.9
]
for
item in items
{
(
"(item) is of type (type(of: item))"
)
}
Running result:
RUNOOB 的类型是 String
43 的类型是 Int
true 的类型是 Bool
9.9 的类型是 Double
Using Any loses type information, and you must cast back with as? to retrieve the value, so don't use it unless truly needed.
AnyObject represents an instance of any class type; it can't represent value types like structs and enums.
Example
// AnyObject represents an instance of any class type
class
Site
{
}
let obj
:
AnyObject
=
Site
(
)
(
type
(
of
:
obj
)
)
Running result:
Site
Never represents the type that "never returns," typically used on functions that inevitably terminate the program or throw.
Example
// Never represents a function that never returns normally
// The program terminates immediately after calling fail, so the following is only a definition demo, not a runtime demo
func fail
(
_ message
:
String
)
Never
{
(
"Fatal error: (message)"
)
fatalError
(
message
)
// The program terminates here
}
Since such functions terminate the program, there's no return value to show; in real projects they're often used to handle unrecoverable errors.
| Type | Meaning | Typical use |
|---|---|---|
| Any | A value of any type | Heterogeneous arrays, dynamic dispatch |
| AnyObject | An instance of any class type | Objective-C interoperability |
| Never | Never returns | fatalError, process-terminating functions |
Type alias typealias
typealias gives an existing type a more readable name without creating a new type.
It's often used to clarify signatures or give short names to complex generic types.
Example
// Give an alias to an existing type
typealias Distance
=
Double
typealias Site
=
(
name
:
String, url
:
String
)
let d
:
Distance
=
9.9
let site
:
Site
=
(
"RUNOOB"
,
"www.runoob.com"
)
(
d
)
(
site.
name
, site.
url
)
Running result:
9.9
RUNOOB www.runoob.com
An alias is fully equivalent to the original type: Distance is Double, and the two can be mixed freely with no implicit conversion issue.
If you need a new type that "can't be mixed with the original," wrap it in a struct or enum rather than using typealias.
Type safety and type inference
Swift is type-safe; no implicit conversion happens between different types.
Adding an integer and a floating-point number requires an explicit conversion; the compiler won't decide for you, avoiding many risks of precision loss.
Example
// Type safety: no implicit conversion between different types
let a
:
Int
=
3
let b
:
Double
=
1.5
// Explicit conversion required: Double(a)
(
Double
(
a
)
b
)
// Type inference
let inferredInt
=
10
// Int
let inferredDouble
=
10.0
// Double
let inferredString
=
"Runoob"
// String
(
type
(
of
:
inferredInt
)
, type
(
of
:
inferredDouble
)
, type
(
of
:
inferredString
)
)
Running result:
4.5
Int Double String
Type inference keeps code concise while type safety surfaces errors earlier; together they're the key to Swift being "both convenient and reassuring."
To inspect a value's type, use type(of:)—not the deprecated dynamicType.
Common questions
Common questions at the data-types stage center on numeric conversion and type selection.
Can Int and Double be added directly
No; you must write Double(a) + b or a + Int(b), and the explicit conversion reminds you to watch for precision loss.
When to use Float instead of Double
Use Float only when memory or bandwidth is tight and precision matters little, such as graphics vertex data; use Double for everyday computing.
How to choose between a tuple and a struct
Use a tuple to temporarily group a few values; define a struct if you need methods, protocols, or reuse.
Why did duplicate elements in a set disappear
By definition a Set has unique elements, so duplicate insertions are ignored; use an array if you need to keep duplicates.
What's the difference between Any and generics
Any loses type information at runtime and requires casting to read values; generics preserve types at compile time, being both flexible and safe—prefer generics over Any.