Swift Standard Library Reference
Swift Standard Library Reference
Contents
Types 5
String 6
Creating a String 6
init() 6
init(count:, repeatedValue:) 6
Querying a String 7
var isEmpty { get } 7
hasPrefix(_ :) -> Bool 7
hasSuffix(_ :) -> Bool 8
Converting Strings 9
toInt() -> Int? 9
Operators 9
+ 9
+= 10
== 11
< 12
Array<T> 13
Creating an Array 13
init() 13
init(count:, repeatedValue:) 13
Accessing Array Elements 14
subscript(Int) -> T { get set } 14
subscript(Range<Int>) -> Slice<T> 15
Adding and Removing Elements 16
append() 16
insert(_ :, atIndex:) 17
removeAtIndex() -> T 18
removeLast() -> T 19
removeAll(keepCapacity: = false) 20
reserveCapacity() 20
Querying an Array 21
var count { get } 21
2
Contents
Dictionary<KeyType, ValueType> 28
Creating a Dictionary 28
init(minimumCapacity: = 2) 28
Accessing and Changing Dictionary Elements 29
subscript(KeyType) -> ValueType? { get set } 29
updateValue(_:, forKey:) -> ValueType? 30
removeValueForKey(_:) -> ValueType? 31
removeAll(keepCapacity: = false) 32
Querying a Dictionary 33
var count { get } 33
var keys { get } 33
var values { get } 34
Operators 34
== 34
!= 35
Numeric Types 36
Boolean Types 36
Integer Types 36
Floating Point Types 37
Protocols 38
Equatable 39
Determining Equality 39
== 39
Comparable 41
3
Contents
Comparing Values 41
< 41
Printable 43
Describing the Value 43
description { get } 43
Free Functions 45
Printing 46
Primary Functions 46
print<T>(_:) 46
println<T>(_:) 46
println() 47
Algorithms 48
Sorting 48
sort<T: Comparable>(inout array: T[]) 48
sort<T>(inout array: T[], pred: (T, T) -> Bool) -> T[] 49
sorted<T: Comparable>(array: T[]) -> T[] 49
sorted<T>(array: T[], pred: (T, T) -> Bool) -> T[] 50
4
Types
● String (page 6)
● Array (page 13)
● Dictionary (page 28)
● Numeric Types (page 36)
5
String
Creating a String
init()
Constructs an empty string.
Declaration
init()
Discussion
Creating a string using this constructor:
init(count:, repeatedValue:)
Constructs a string with a single character repeated a given number of times.
Declaration
6
String
Querying a String
Discussion
The resulting string contains the supplied repeatedValue character, repeated count times:
Querying a String
Declaration
Discussion
Use this read-only property to query whether the string is empty, which means it has no characters:
string = ""
Declaration
7
String
Querying a String
Discussion
Use this method to determine whether the characters in a given string match exactly against the characters
at the beginning of the receiver:
Declaration
Discussion
Use this method to determine whether the characters in a given string match exactly against the characters
at the end of the receiver:
8
String
Converting Strings
Converting Strings
Declaration
Discussion
Use this method to convert a string of characters into an integer value. The method returns an optional—if
the conversion succeeded, the value will be the resulting integer; if the conversion failed, the value will be
nil:
} else {
Operators
+
Concatenates two strings, or a string and a character, or two characters.
Declaration
9
String
Operators
Discussion
Use the + operator to concatenate two strings:
If the value supplied on the left hand side of the operator is an empty string, the resultant value is the unmodified
value on the right hand side.
You can use the + operator with two strings as shown in the combination example, or with a string and a
character in either order:
+=
Appends a string or character to an existing string.
Declaration
10
String
Operators
Discussion
Use the += operator to append a string or character at the end of an existing string:
If the initial string is empty, the resultant value is the unmodified rhs value.
You can use the += operator to append either another string, or a character:
You can only use the += operator to append if you declared the original string or character using the var
keyword (that is, as a variable and not a constant):
// Error: could not find an overload for '+=' that accepts the supplied arguments
==
Determines the equality of two strings.
Declaration
Discussion
Evaluates to true if the two string values contain exactly the same characters in exactly the same order:
11
String
Operators
<
Performs a lexicographical comparison to determine whether one string evaluates as less than another.
Declaration
Discussion
Evaluates to true if the lhs value is less than the rhs value, by performing a lexicographical comparison of
the characters:
12
Array<T>
An Array is a generic type that manages an ordered collection of items, all of which must be of the same
underlying type (T).
Creating an Array
init()
Constructs an empty array of type T.
Declaration
init()
Discussion
Creating an array using this constructor:
init(count:, repeatedValue:)
Constructs an array with a given number of elements, each initialized to the same value.
13
Array<T>
Accessing Array Elements
Declaration
Discussion
The resulting array will have count elements in it, each initialized to the same value provided as the value for
repeatedValue.
For example:
Declaration
Discussion
Use subscripting to access the individual elements in any array:
14
Array<T>
Accessing Array Elements
If you declare the array using the var keyword (that is, as a variable), you can also use subscripting to change
the value of any existing element in the array:
subscriptableArray[0] = "nothing"
It is not possible to insert additional items into the array using subscripting:
Instead, use the append() (page 16) function, or the += (page 26) operator.
You cannot use subscripting to change the value of any existing element in an array that you declare using
the let keyword (that is, as a constant):
Declaration
Discussion
Use range subscripting to access one or more existing elements in any array:
15
Array<T>
Adding and Removing Elements
If you declare the array using the var keyword (that is, as a variable), you can also use subscripting to change
the values of a range of existing elements:
You do not need to provide the same number of items as you are replacing:
subscriptableArray[1...2] = []
It is not possible to insert additional items into the array using subscripting:
You cannot use subscripting to change any values in an array that you declare using the let keyword (that
is, as a constant):
Instead, use the append() (page 16) function, or the += (page 26) operator.
append()
Adds a new item as the last element in an existing array.
Declaration
16
Array<T>
Adding and Removing Elements
Discussion
Use this method to add a new item to an existing array. The new element will be added as the last item in the
collection:
// array is [0, 1, 2]
array.append(3)
// array is [0, 1, 2, 3]
You can only append new values to an array if you declared the array using the var keyword (that is, as a
variable and not a constant):
// Error: immutable value of type '[Int]' only has mutating members named 'append'
insert(_ :, atIndex:)
Inserts an element into the collection at a given index.
Declaration
Discussion
Use this method to insert a new element anywhere within the range of existing items, or as the last item:
// array is [0, 1, 2, 3]
The index must be less than or equal to the number of items in the collection. If you attempt to insert an item
at a greater index, you’ll trigger an assertion:
17
Array<T>
Adding and Removing Elements
array.insert(6, atIndex: 6)
You can only insert new values in an array if you declared the array using the var keyword (that is, as a variable
and not a constant):
// Error: immutable value of type '[Int]' only has mutating members named 'insert'
removeAtIndex() -> T
Removes the element at the given index and returns it.
Declaration
Discussion
Use this method to remove an element at the given index. The return value of the method is the element
that was removed:
// removed is 0
The index must be less than the number of items in the collection. If you attempt to remove an item at a greater
index, you’ll trigger an assertion:
array.removeAtIndex(5)
You can only remove an element from an array if you declared the array using the var keyword (that is, as a
variable and not a constant):
18
Array<T>
Adding and Removing Elements
// Error: immutable value of type '[Int]' only has mutating members named
'removeAtIndex'
removeLast() -> T
Removes the last element from the collection and returns it.
Declaration
Discussion
Use this method to remove the last element in the receiver. The return value of the method is the element
that was removed:
// removed is 3
There must be at least one element in the array before you call this method—if you call this method on an
empty array, you’ll trigger an assertion:
You can only remove the last item from an array if you declared the array using the var keyword (that is, as a
variable and not a constant):
// Error: immutable value of type '[Int]' only has mutating members named
'removeLast'
19
Array<T>
Adding and Removing Elements
removeAll(keepCapacity: = false)
Removes all the elements from the collection, and by default clears the underlying storage buffer.
Declaration
Discussion
Use this method to remove all of the elements in the array:
Unless you specify otherwise, the underlying backing storage will be cleared.
You can only remove all items from an array if you declared the array using the var keyword (that is, as a
variable and not a constant):
// Error: immutable value of type '[Int]' only has mutating members named 'removeAll'
reserveCapacity()
Ensures that the underlying storage can hold the given total number of elements.
Declaration
Discussion
Ensure that the array has enough contiguous underlying backing storage to store the total number of elements
specified for minimumCapacity.
20
Array<T>
Querying an Array
Querying an Array
Declaration
Discussion
Use this read-only property to query the number of elements in the array:
array += "three"
Declaration
Discussion
Use this read-only property to query whether the array is empty:
21
Array<T>
Algorithms
array.removeAll()
Declaration
Discussion
Use this read-only property to query how many total elements the array can store without triggering a
reallocation of the backing storage.
Algorithms
sort(_ :)
Sorts the receiver in place using a given closure to determine the order of a provided pair of elements.
Declaration
Discussion
Use this method to sort elements in the receiver. The closure that you supply for isOrderedBefore should
return a Boolean value to indicate whether one element should be before (true) or after (false) another
element:
// array is [1, 2, 3, 4, 5]
22
Array<T>
Algorithms
array.sort { $1 < $0 }
// array is [5, 4, 3, 2, 1]
You can only use sort an array in place if you declared the array using the var keyword (that is, as a variable):
// Error: immutable value of type [Int] only has mutating members named 'sort'
Declaration
Discussion
Use this method to return a new array containing sorted elements from the receiver. The closure that you
supply for isOrderedBefore should return a Boolean value to indicate whether one element should be
before (true) or after (false) another element:
23
Array<T>
Algorithms
Declaration
Discussion
Use this method to return an array containing the elements of the receiver in reverse order; that is, the last
item will be the first, the penultimate will be the second, and so on:
Declaration
Discussion
Use this method to return a new array by filtering an existing array. The closure that you supply for
includeElement: should return a Boolean value to indicate whether an element should be included (true)
or excluded (false) from the final collection:
Declaration
24
Array<T>
Algorithms
Discussion
Use this method to return a new array containing the results of applying a provided closure to transform each
element in the receiver:
Declaration
Discussion
Use this method to reduce a collection of elements down to a single value by recursively applying the provided
closure:
25
Array<T>
Operators
2. Next, the closure is called with the previous result as the first argument, and the second element as the
second argument.
In the addResult case, that means a result of 1 and the next item 2: { 1 + 2 }.
In the multiplyResult case, that means a result of 1 and the next item 2: { 1 * 2 }.
3. The closures continue to be called with the previous result and the next element as arguments:
In the addResult case, that means {3 + 3}, {6 + 4}, {10 + 5}, with a final result of 15.
In the multiplyResult case, that means {2 * 3}, {6 * 4}, {24 * 5}, with a final result of 120.
Operators
+=
Appends an element or sequence of elements to an existing array.
Declaration
Discussion
The += operator offers an easy way to append a single element or a sequence of elements to the end of an
existing array:
// array is [0, 1, 2, 3]
array += [4, 5, 6]
// array is [0, 1, 2, 3, 4, 5, 6]
The type of the element or elements must match the type of the existing elements in the array:
array += "hello"
// Error: could not find an overload for '+=' that accepts the supplied arguments
26
Array<T>
Operators
You can only append new values to an array if you declared the array using the var keyword (that is, as a
variable and not a constant):
// Error: could not find an overload for '+=' that accepts the supplied arguments
27
Dictionary<KeyType, ValueType>
A Dictionary is a generic type that manages an unordered collection of key-value pairs. All of a dictionary's
keys must be compatible with its key type (KeyType). Likewise, all of a dictionary's values must be compatible
with its value type (ValueType).
Creating a Dictionary
init(minimumCapacity: = 2)
Constructs an empty dictionary with capacity for at least the specified number of key-value pairs.
Declaration
init(minimumCapacity: Int = 2)
Discussion
You can create a dictionary using this constructor without specifying a value for minimumCapacity, in which
case its default value of 2 will be used:
If you do provide a minimumCapacity value, note that the actual capacity reserved by the dictionary may be
larger than the value you provide.
Creating a dictionary using this constructor is equivalent to using the convenience syntax:
28
Dictionary<KeyType, ValueType>
Accessing and Changing Dictionary Elements
Declaration
Discussion
Use subscripting to access the individual elements in any dictionary. The value returned from a dictionary's
subscript is of type ValueType?—an optional with an underlying type of the dictionary’s ValueType:
In this example, value is of type Int?, not Int. Use optional binding to query and unwrap a dictionary
subscript's return value if it is non-nil:
You can also use subscripting to change the value associated with an existing key in the dictionary, add a new
value, or remove the value for a key by setting it to nil:
dictionary["three"] = 33
dictionary["four"] = 4
dictionary["three"] = nil
29
Dictionary<KeyType, ValueType>
Accessing and Changing Dictionary Elements
Values in a dictionary can be changed, added, or removed with subscripting only if the dictionary is defined
with the var keyword (that is, if the dictionary is mutable):
// Error: could not find an overload for 'subscript' that accepts the supplied
arguments
Declaration
Discussion
Use this method to insert or update a value for a given key, as an alternative to subscripting. This method
returns a value of type ValueType?—an optional with an underlying type of the dictionary’s ValueType:
In this example, previousValue is of type Int?, not Int. Use optional binding to query and unwrap the
return value if it is non-nil:
} else {
30
Dictionary<KeyType, ValueType>
Accessing and Changing Dictionary Elements
Values in a dictionary can be updated using this method only if the dictionary is defined with the var keyword
(that is, if the dictionary is mutable):
// Error: immutable value of type '[String: Int]' only has mutating members named
'updateValue'
Declaration
Discussion
Use this method to remove a value for a given key, as an alternative to assigning the value nil using
subscripting. This method returns a value of type ValueType?—an optional with an underlying type of the
dictionary’s ValueType:
In this example, previousValue is of type Int?, not Int. Use optional binding to query and unwrap the
return value if it is non-nil:
} else {
31
Dictionary<KeyType, ValueType>
Accessing and Changing Dictionary Elements
Values in a dictionary can be removed using this method only if the dictionary is defined with the var keyword
(that is, if the dictionary is mutable):
// Error: immutable value of type '[String, Int]' only has mutating members named
'removeValueForKey'
removeAll(keepCapacity: = false)
Removes all key-value pairs from the dictionary, and by default clears up the underlying storage buffer.
Declaration
Discussion
Use this method to remove all of the key-value pairs in the dictionary:
Unless you specify otherwise, the underlying backing storage will be cleared.
Values in a dictionary can be removed using this method only if the dictionary is defined with the var keyword
(that is, if the dictionary is mutable):
// Error: immutable value of type '[String, Int]' only has mutating members named
'removeAll'
32
Dictionary<KeyType, ValueType>
Querying a Dictionary
Querying a Dictionary
Declaration
Discussion
Use this read-only property to query the number of elements in the dictionary:
Declaration
Discussion
Use this read-only property to retrieve an iterable collection of a dictionary’s keys:
To use a dictionary’s keys with an API that takes an Array instance, initialize a new array with the keys property:
33
Dictionary<KeyType, ValueType>
Operators
Declaration
Discussion
Use this read-only property to retrieve an iterable collection of a dictionary’s values:
To use a dictionary’s values with an API that takes an Array instance, initialize a new array with the values
property:
Operators
==
Determines the equality of two dictionaries.
34
Dictionary<KeyType, ValueType>
Operators
Declaration
Discussion
Evaluates to true if the two dictionaries contain exactly the same keys and values:
!=
Determines the inequality of two dictionaries.
Declaration
Discussion
Evaluates to true if the two dictionaries do not contain exactly the same keys and values:
35
Numeric Types
The Swift standard library contains many standard numeric types, suitable for storing Boolean, integer, and
floating-point values.
Boolean Types
Swift includes one Boolean type, Bool, which may be either true or false.
Integer Types
The primary integer type in Swift is Int, which is word-sized. This means that it holds 32 bits on 32-bit platforms,
and 64 bits on 64-bit platforms.
For the majority of use cases, you should use the base Int type.
If you require a type with a specific size or signedness, for example to work with raw data, Swift also includes
the following types:
UInt8 0 255
UInt16 0 65,535
UInt32 0 4,294,967,295
UInt64 0 18,446,744,073,709,551,615
36
Numeric Types
Floating Point Types
37
Protocols
38
Equatable
The Equatable protocol makes it possible to determine whether two values of the same type are considered
to be equal.
Determining Equality
==
Determines the equality of two values of the same type.
Declaration
Discussion
To conform to the protocol, you must provide an operator declaration for == at global scope. You should return
true if the provided values are equal, otherwise false.
39
Equatable
Determining Equality
40
Comparable
The Comparable protocol makes it possible to compare two values of the same type.
There is one required operator overload defined in the protocol (<), as well as one defined in the inherited
Equatable (page 39) protocol (==). By adopting the Comparable protocol and adding an operator overload
for <, you automatically gain the ability to use >, <=, and >=.
Comparing Values
<
Determines whether one value is less than another value of the same type.
Declaration
Discussion
To conform to the protocol, you must provide an operator declaration for < at global scope. You should return
true if the lhs value is less than the rhs value, otherwise false.
41
Comparable
Comparing Values
42
Printable
The Printable protocol allows you to customize the textual representation of any type ready for printing (for
example, to Standard Out).
A type must adopt this protocol if you wish to supply a value of that type to, for example, the print<T>(_:) (page
46) and println<T>(_:) (page 46) functions.
description { get }
A string containing a suitable textual representation of the receiver (read-only).
Declaration
Discussion
This property is required for any type that adopts the Printable protocol. Use it to determine the textual
representation to print when, for example, calling the print<T>(_:) (page 46) and println<T>(_:) (page 46)
functions:
43
Printable
Describing the Value
44
Free Functions
45
Printing
There are two primary functions for printing values to Standard Out in the Swift standard library: print()
and println(). The println() function is overloaded to receive either a value to print, or no value, in which
case it prints a newline character.
Both functions are global free functions, which means they may be called in their own right without a receiver:
print("Hello, world!\n")
println("Hello, world!")
Primary Functions
print<T>(_:)
Writes the textual representation of a provided value to Standard Out.
Declaration
func print<T>(object: T)
Discussion
The value you supply for object must conform to the Printable (page 43) or DebugPrintable (page $@)
protocol:
print("Hello, world\n")
println<T>(_:)
Writes the textual representation of a provided value, followed by a newline character, to Standard Out.
46
Printing
Primary Functions
Declaration
func println<T>(object: T)
Discussion
The value you supply for object must conform to the Printable (page 43) or DebugPrintable (page $@)
protocol:
println("Hello, world")
println()
Writes a newline character to Standard Out.
Declaration
func println()
Discussion
Call this function without any values to print a newline character to Standard Out:
print("Hello, world")
println()
47
Algorithms
The Swift standard library contains a variety of algorithms to aid with common tasks, including sorting, finding,
and many more.
Sorting
Declaration
Discussion
Use this method to sort a mutable array in place using the standard < (page 41) operator. All values in the
array must be of types that conform to the Comparable (page 41) protocol, which inherits from the
Equatable (page 39) protocol:
// array is [1, 2, 3, 4, 5, 6]
You can only use this method with an array declared using the var keyword (that is, a variable):
48
Algorithms
Sorting
Declaration
Discussion
Use this method to sort a mutable array of elements in place using a closure. The closure must return a Boolean
value to indicate whether the two items are in ascending order (true) or descending order (false):
// array is [6, 5, 4, 3, 2, 1]
You can only use this method with an array declared using the var keyword (that is, a variable):
Declaration
Discussion
Use this method to sort using the standard < (page 41) operator. All values in the provided array must be of
types that conform to the Comparable (page 41) protocol, which inherits from the Equatable (page 39)
protocol:
49
Algorithms
Sorting
// result is [1, 2, 3, 4, 5, 6]
Declaration
func sorted<T>(var array: T[], pred: (T, T) -> Bool) -> T[]
Discussion
Use this method to sort an array of elements using a closure. The closure must return a Boolean value to indicate
whether the two items are in ascending order (true) or descending order (false):
50
Document Revision History
Date Notes
2014-09-17 New document that describes the key structures, classes, protocols, and
free functions available in the Swift Standard Library.
51
Apple Inc.
Copyright © 2014 Apple Inc.
All rights reserved.