Você está na página 1de 137

J.

Shapiro

For
Swift 2.0

Swift
Code Cookbook
Over 120 simple and practical recipes
for Mac OS X and iOS development
Swift
Code Cookbook

John Shapiro

InSilico
Swift Code Cookbook
by John Shapiro


Copyright © 2015 InSili.co. All rights reserved.


October 2015: First Edition



Swift is a trademark of Apple Inc., registered in the U.S. and other countries.


While the publisher and the authors have used good faith efforts to ensure
that the information and instructions contained in this work are accurate, the
publisher and the authors disclaim all responsibility for errors or omissions,
including without limitation responsibility for damages resulting from the use
of or reliance on this work. Use of the information and instructions contained
in this work is at your own risk. If any code samples or other technology this
work contains or describes is subject to open source licenses or the intellec-
tual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.
Preface

Long textbooks and huge references What this book is:


manuals are nice. But only for taking
up space in our bookcase. • A quick Swift reference
• A collection of useful hand-picked
What most programmers really want code snippets that solve everyday
is a handy pocket book that they can coding problems - all organized by
carry with them, use it for reference at categories
any time and cherry-pick the exact
piece of information they need at that What is included :

specific moment - pretty much like a
chef which wants to quickly look up 1. Basics
some ingredient and make sure he got 2. Functions
the recipe right.
 3. Classes

 4. Closure
And this is how Swift Code Cookbook 5. Strings
was born.
 6. Arrays

 7. Dictionaries
What this book is not:
 8. Numbers
9. Exceptions
• A real cookbook (if you expect to find 10.Files
your next curry recipe here, I’m sorry 11.Date/Time
but I’ll have to let you down...) 12.Shell
• A complete Swift Reference 13.Web

• A collection of every possible solu- 

tion to every possible Swift-related
problem you can think of
0 “Start by doing what's necessary;
then do what's possible;

Introduction and suddenly you are doing


the impossible.”

– Francis of Assisi

v
0.1 How to Run Swift

Our first program

So, fire up your favorite editor (if you still haven’t made up your mind – self-promotion com-
ing lol – have a look at Peppermint) and let’s write this very… complicated one line of
code.

print("Hello Swift!");

Now we already have our code file, let’s save this as hello.swift. The next rather logical
question is: how do we actually run this thing?

Executing it

Well, you might be expecting something along the lines of “Open Xcode, etc, etc” – but
since I’m rather old-school and prefer having total control over what goes on, why/how it
is executed, what could be better than doing it straight from the command line?


So, just open Terminal and let’s go to the location where your hello.swift resides. Now, all
there’s left – provided that you already have Xcode installed – is running our script:

swift hello.swift


And this is what it looks like:

vi
That was easy, wasn’t it? Pretty much like with any scripting language (see: php, python,
ruby, perl, etc). But wait: is Swift a scripting language? Well, not quite…


Compiling it

What if we actually want to compile this code of ours and have a binary, which we can
then use — without having to re-compile or having the Swift compiler around?

Let’s see…

xcrun swiftc hello.swift

Super-easy again. Just note the use of swiftc (the swift “compiler”) instead of swift. Now,
if you look again into your folder contents, you’ll notice a single hello binary, which you
can execute – as any normal binary

./hello

And that was it.

0.2 Scripting in Swift

So, can Swift be used for Scripting, pretty much like any regular interpreted language –
like PHP, Python, Ruby, Perl or… even Bash?

Well, here’s the catch: given its speed, it sure can – at least for smaller scripts. Plus, since
Apple has already announced its future release as open-source software (which impli-
es ports to Linux, Windows and the rest of the systems), this makes it a not so Mac-only
thing.

So, the answer is: why not?

vii
Our first “script”

Let’s get started then, with the same… ultra-complex “Hello World” we played with in the
previous section (0.1)

And now let’s add the magic shebang line:

#!/usr/bin/env xcrun swift


print("Hello Swift!")

We save it as hello_script.swift. And that was it.

Executing it

Once we make it “officially” executable by:

sudo chmod +x hello_script.swift

We can now execute it as we would execute any script:

./hello_script.swift

viii
ix
1
Basics “The secret of getting ahead is
getting started.”


– Mark Twain
1.1 Create a Hello World app

Problem
I want to create a minimal Hello World program in Swift.

Solution


// Just one line of code


print("Hello World!")

1.2 Declare a constant

Problem
I want to declare a new constant and assign it a value.

Solution


// This is an Integer constant


let a : Int = 2

// This is a String constant


let b : String = "My string"

// This is an Integer constant - no need to declare a type,


// since it's inferred from the right-hand side value
var c = 5


11
1.3 Declare a variable

Problem
I want to declare a new variable (Integer, String, Array, Dictionary) and/or assign it an initial
value.

Solution


// This is an Integer variable


var a : Int

// This is a String variable, initialized


var b : String = "My string"

// This is an Integer variable - no need to declare a type,


// since it's inferred from the right-hand side value
var c = 2

// An Array variable
var d = [1,2,3]

// Another array - also declaring the type


var e : [String] = ["one","two","three"]

// A Dictionary
var f = ["name": "John", "surname": "Doe"]

// An empty Dictionary
var g : [String:String] = [:]

12
1.4 Write a For loop

Problem
I want to create a For loop.

Solution


// Creating our loop - C-style

for var x=0; x<10; x++ {


print(x)
}

// Our loop - pure Swift-style

for var y in 0..<10 {


print(y)
}

1.5 Write a While loop

Problem
I want to create a While loop.

Solution


// Creating our loop

var x = 0

// Count from 0 to 9

while x<10 {
print(x)
x++
}

13
1.6 Write an If-Else statement

Problem
I want to write an if-else conditional statement.

Solution


// Set a boolean variable


let swiftIsCool = true

if swiftIsCool {
print("Of course it is!")
}
else {
print("Ooops")
}

1.7 Write a Switch-Case statement

Problem
I have a list of different conditions and want to write a Switch-Case statement.

Solution


let name = "John"

switch name {
// List the different cases
// - no "break" needed

case "John" : print("Hello John!")


case "Jane" : print("Hello Jane!")
default : print("Hello!")
}

14

15
2 “When it is obvious that the goals
Functions cannot be reached, don't adjust
the goals, adjust the action steps.”

– Confucius
2.1 Declare a function

Problem
I want to declare a new function and call it.

Solution


// Declare our new function


func myFunc() {
print("Hello from myFunc!")
}

// Call it
myFunc()

2.2 Declare a function with arguments

Problem
I want to declare a new function, which takes some arguments, and then call it.

Solution


// Declare our new function


func sayHelloTo(name:String) {
print("Hello \(name)!")
}

// Call it
sayHelloTo("John")

17
2.3 Declare a function with return type

Problem
I want to declare a new function which takes some arguments and returns a result.

Solution


// Declare our new function


func multiply(a:Int, with:Int)->Int {
return a*with
}

// Call it
let product = multiply(2, with:5)

print(product)

2.4 Declare a function with default values

Problem
I want to declare a function which takes one or more parameters, with default values.

Solution


// Declare a function with one parameter


// which has a default value set
func sayHello(whom : String = "World") {
print ("Hello \(whom)!")
}

// Call it without any parameter


// and the 'default' one will be used
sayHello()

// Let's call it again


// with some parameter
sayHello("John")

18
2.5 Declare a function with inout parameters

Problem
I want to declare a function with parameters which it can alter, and call it with a reference.

Solution


// Declare a function with 'inout' parameters


func append(inout str:String, withString:String) {
str += withString
}

// Declare string variable


var myString = "Hello"

// Call the function with a reference - &


// to our 'myString' variable
append(&myString, withString:" World!")

// The string variable will have now changed


print(myString)

19
2.6 Declare a function with variadic arguments

Problem
I want to declare and call a function which takes a variable number of arguments.

Solution


// Declare our function which takes


// a variable number of Integer arguments
func sum(numbers: Int...) -> Int {
var result = 0
for number in numbers {
result += number
}

return result
}

// Call it with just 2 parameters


let sum1 = sum(1,2)
print(sum1)

// Call it with even more parameters


let sum2 = sum(1,2,3,4,5,6)
print(sum2)

20
21
3
“Any program is only as good
Classes as it is useful.”


– Linus Torvalds
3.1 Declare a class

Problem
I want to create a new class and create a new instance of it.

Solution


// Declare our new class

class myClass {

init() {
// Called when a new object is created
print("A new instance was created!")
}

// Create a new object of myClass


let c = myClass()

23
3.2 Declare a class with functions

Problem
Declare a new class with its own functions/methods, create a new instance and call its
methods from the outside.

Solution


// Declare our new class

class mathClass {

func add(a:Int, with:Int)->Int {


return a+with;
}

func multiply(a:Int, with:Int)->Int {


return a*with;
}
}

// Create a new instance of the mathClass


let math = mathClass();

print(math.add(1, with:1));
print(math.multiply(2, with:5));

24
3.3 Declare a class with inheritance

Problem
I have a parent class and want to create another one which "inherits" it.

Solution


// Create 'parent' class


class Animal {

func sayHello() {
print("Hello")
}
}

// Create a child class


// which 'inherits' our parent class
class Dog : Animal {

// Create a new Dog instance


let myDog = Dog()

// We can also access its parent's methods


myDog.sayHello()

25
3.4 Declare a class with properties

Problem
I want to declare a new class with its own properties, create a new instance and also be
able to access its properties.

Solution


// Declare our new class

class myClass {

var myProperty : String

init(prop: String) {
// Called when a new object is created
myProperty = prop
}

// Create a new object of myClass


let c = myClass(prop:"my property")

print(c.myProperty)

26
3.5 Extend an existing class

Problem
I want to extend an existing class and add my own methods/functions to it.

Solution


// Extend the Int class


extension Int {

// Add a method called 'multiply'


func multiply(x:Int)->Int {
return self*x
}
}

// Now, all our Int's have the extra method


let y = 2.multiply(5)

print(y)

27
3.6 Implement a singleton class

Problem
I want to create a Singleton class.

Solution


// Creating our Singleton

class SharedManager {
// Declare our 'sharedInstance' property
static let sharedInstance = SomeManager()

// Set an initializer -
// it will only be called once
init() {
print("SomeManager initialized")
}

// Add a test function


func doSth() {
print("I'm doing something")
}
}

// The 'init' function will


// only be called the first time
SharedManager.sharedInstance.doSth()
SharedManager.sharedInstance.doSth()

28
29
4 “Innovation distinguishes 

Closures between a leader and 

a follower.”


– Steve Jobs
4.1 Declare a closure

Problem
I want to declare and use a simple closure.

Solution


// Declare our closure


let myClosure = {
print("Hello from myClosure!")
}

// Call it
myClosure()

4.1 Declare a closure with arguments

Problem
I want to declare a closure that takes one or more parameters and/or returns some result.

Solution


// Declare a closure with 2 integer arguments


// returning an Integer
let multiply = {(x:Int,y:Int)->Int in
return x*y
}

// Call it
let result = multiply(2,5)
print(result)

31
4.1 Use closure as a parameter

Problem
I want to declare a function that takes a closure as a parameter and then call it.

Solution


// Declare a function
// that takes a closure (with 2 integer parameters)
// as an argument

func doSth(action:(Int,Int)->()) {
// Run the passed 'action'
// with the parameters: 2, 5
action(2,5);
}

// Call it
doSth({(x:Int, y:Int)->() in
print("x * y = \( x * y )")
});

32
33
5 “There is geometry in the humming
Strings of the strings, there is music in the
spacing of the spheres.”


– Pythagoras
5.1 Declare a string variable

Problem
I want to create a string variable and set its value.

Solution

// String literal
var a = "Hello World"

5.2 Append string to string

Problem
I want to append a String to another String.

Solution

// String literal
var a = "Hello "

// Append something
a += "World!"
print(a)

35
5.3 Concatenate strings

Problem
I want to concatenate 2 or more strings.

Solution

// String literals
let a = "Hello "

// Concatenate them
var c = a + "World!"
print(c)

5.4 Check if 2 strings are equal

Problem
I have two strings and want to check if they are equal (if it's the same string).

Solution

// String literals
let s1 = "Hello World"
let s2 = "Hello Guys"

// Check they are the same

if s1==s2 {
print("S1 is the same as S2")
}
else {
print("S1 is not the same as S2")
}

36
5.5 Check if object is a string

Problem
I have an object and want to check if it's a String object.

Solution

// String literal
let s = "Hello World"

// Check if 's' is a String

if s is String {
print("Yes, it's a String")
}

5.6 Get the length of a string

Problem
I have a String and want to calculate its length.

Solution

// String literal
let s = "Hello world"

// Get the length of the string

let length = s.characters.count


print(length)

37
5.7 Check if string contains string

Problem
I want to check if a string contains another string.

Solution

// String literal
let s = "Hello World"

// Check if it contains 'Hello'

if s.rangeOfString("Hello") != nil {
print("Yes it contains 'Hello'")
}

5.8 Check if string contains regex

Problem
I want to check if a string contains a specific regular expression.

Solution

// String literal
let s = "Hello World"

// Check if it contains one or more 'l's

if s.rangeOfString("l+", options: .RegularExpressionSearch) != nil {


print("Yes it does")
}

38
5.9 Check if string has prefix

Problem
Check if string has a given prefix.

Solution

// String literal
var a = "Hello World!"

// Check if there is a specific Prefix

if a.hasPrefix("Hell") {
print("Yes, there is")
}

5.10 Check if string has suffix

Problem
Check if string has a given suffix.

Solution

// String literal
var a = "Hello World!"

// Check if there is a specific Suffix

if a.hasSuffix("World!") {
print("Yes, there is")
}

39
5.11 Check if string is empty

Problem
I want to check if a string is empty.

Solution

// String literal
var a = "Hello World!"

// Check if it is empty

if a.isEmpty {
print("Ooops, it's empty")
}

5.12 Use string interpolation

Problem
I have a string and I want to embed variable values within this string.

Solution

// String literal
var username = "John"

// Let's print this string


// along with a 'hello' message

print("Hello \(username)");

40
5.13 Convert a string to Lowercase

Problem
I want to convert a string to lowercase.

Solution

// String literal
var a = "Hello World!"

// Lowercase the string


a = a.lowercaseString
print(a)

5.14 Convert a string to Uppercase

Problem
I want to convert a string to uppercase.

Solution

// String literal
var a = "Hello World!"

// uppercase the string


a = a.uppercaseString
print(a)

41
5.15 Capitalize all words in a string

Problem
I have a string and want to capitalize all the "words" in it.

Solution

// String literal
let s = "hello horld"

// Replace "World" with "Guys"


let b = s.capitalizedString
print(b)

42
5.16 Compare 2 strings

Problem
I have two strings and want to compare them lexicographically (what comes first in a "dic-
tionary").

Solution

// String literals
let s1 = "Hello World"
let s2 = "Hello Guys"

// Compare the 2 strings, lexicographically

if s1<s2 {
print("S1 comes before S2")
}
else {
print("S1 comes after S2")
}

43
5.17 Loop through characters in string

Problem
I have a String and want to iterate through its characters.

Solution

// Initialize the Array
var str = "Hello World"

// Loop through its individual characters

str.characters.forEach {
print($0)
}

5.18 Get substring from range

Problem
I have a string and want to retrieve a substring found within a specific range.

Solution

// String literal
let s = "Hello World"

// Get the substring from position 6


// to the end: 'World'

let sub = s[s.startIndex.advancedBy(6)..<s.endIndex]


print(s)

44
5.19 Replace string in string

Problem
I have a string and want to replace all occurrences of a substring with another string.

Solution

// String literal
let s = "Hello World"

// Replace "World" with "Guys"

let b = s.stringByReplacingOccurrencesOfString("World", withString:"Guys")


print(b)

5.20 Reverse a string

Problem
I have a string and want to reverse it (with all of its characters in the reverse order).

Solution

// String literal
let s = "Hello World"

// Reverse its characters

let reversed = String(s.characters.reverse())


print(reversed)

45
5.21 Repeat a string

Problem
I want to repeat a string several times.

Solution

// String literal
var s : String

// Set 's' to 5 x "Hello"

for var i in 0..<5 {


s += "Hello"
}
print(s)

5.22 Split a string by another string

Problem
I have a String and I want to split it, by using another string, into an array of sub-strings.

Solution

// String literals
let s = "Hello World"

// Split it by "o"
var a = s.componentsSeparatedByString("o")
print(a)

46
5.23 Trim whitespace from a string

Problem
I want to remove all leading and trailing whitespace from a string.

Solution

// String literal
var s = " Hello World! "

// Trim all whitespace

s = s.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

print(s)

5.24 Generate a unique identifier

Problem
I want to create a random UUID (unique identifier string).

Solution

// Create the Unique Identifier

let uuid = NSUUID().UUIDString


print(s)

47
48
6
“Great things are done by a series
Arrays of small things brought together.”


– Vincent Van Gogh


6.1 Create an empty array

Problem
I want to create/initialize an empty Array.

Solution

// Initialize the Array - Solution A
let a1 = [Int]()

// Initialize the Array - Solution B


let a2 : [Int] = []

6.2 Create an array with values

Problem
I want to create a new Array and set some values.

Solution

// Initialize the Array
let a = [“one”,”two”,”three”];

print(a)

50
6.3 Append item to array

Problem
I want to append an item to an existing Array.

Solution

// Initialize the Array
var a = [1,2,3]

// Append another item - solution A


a += [4]

// Append another item - solution B


a.append(5)

print(a)

6.4 Append array to array

Problem
I want to append an Array to another Array.

Solution

// Initialize the Array
var a = [1,2,3]

// Append another array


a += [4,5,6]
print(a)

51
6.5 Set array element at index

Problem
I have an array and want to set a new value to one of its elements, by index.

Solution

// Initialize the Array
var arr = ["one", "two", "three"]

// Set element at index: 1


arr[1] = "TWO"

print(arr)

6.6 Get array element at index

Problem
I have an array and want to a get a specific element, by index.

Solution

// Initialize the Array
var arr = ["one", "two", "three"]

// Get element at index: 1


print(arr[1])

52
6.7 Get first element from array

Problem
I want to get the first element of an Array.

Solution

// Initialize the Array
let arr = ["one", "two", "three"]

// Get the first element


let firstElement = arr.first
print(firstElement)

6.8 Get last element from array

Problem
I want to get the last element of an Array.

Solution

// Initialize the Array
let arr = ["one", "two", "three"]

// Get the last element


let lastElement = arr.last
print(lastElement)

53
6.9 Check if object is an array

Problem
I have an object and want to check if it's an Array object.

Solution

// Initialize the array

let arr = [1,2,3]

// Check if 'arr' is an Array

if arr is Array {
print("Yes, it's an Array")
}

6.10 Remove all items from array

Problem
I want to remove all elements from an existing array.

Solution

// Initialize the Array
var a = [1,2,3]

// Remove all elements

a.removeAll()

print(a)

54
6.11 Remove item at array index

Problem
I have an Array and want to delete an item at a specifix index position.

Solution

// Initialize the Array
var a = [1,2,3]

// Remove item at index: 2


a.removeAtIndex(2)

print(a)

6.12 Remove item from array by value

Problem
I have an array and want to remove one (or more) element based on a specific value.

Solution

// Initialize the Array
var a = ["one", "two", "three"]

// Remove/filter item with value 'two'

a = a.filter { $0 != "two" }
print(a)

55
6.13 Remove duplicates from array

Problem
I have an array and want to remove all duplicate elements.

Solution

// Initialize the Array
var a = [1,2,3,4,5,2,4,1,4,3,6,5]

// Remove duplicates:
// first by converting to a Set
// and then back to Array
a = Array(Set(a))

print(a)

6.14 Reduce array to a single value

Problem
I have an array and want to recursively perform a specific action on all elements and get
one single value/result.

Solution

// Initialize the Array
var a = [1,2,3,4,5,6]

// Recursively perform the defined action ($0 + $1)


// to all elements and get result

var sum = a.reduce(0) { $0 + $1 }


print(sum)

56
6.15 Loop through array

Problem
I have an array and want to iterate through all of its elements.

Solution

// Initialize the Array
var arr = ["one", "two", "three"]

// Iterate through the array

for element in arr {


print(element)
}

6.16 Loop through array with index

Problem
I have an array and want to iterate through all of its elements, by knowing the index of
each element.

Solution

// Initialize the Array
var arr = ["one", "two", "three"]

// Iterate through the array


// keeping track of the elements' index

for (index,element) in arr.enumerate() {


print("\(index) = \(element)")
}

57
6.17 Get the size of an array

Problem
I have an Array and want to calculate its size/capacity (how many elements it contains).

Solution

// Initialize the Array
var a = [1,2,3]

// Get the size of the array

let size = a.count


print(size)

6.18 Find element index in array by value

Problem
I have an Array and want to get the index of the first occurrence (if any) of a specific ele-
ment.

Solution

// Initialize the Array
let arr = ["one", "two", "three", "four"]

// Find first occurence of "two" (if any)


var location = arr.indexOf("two")

print(location!)

58
6.19 Get minimum element from array

Problem
I have an array and want to get the minimum element (lowest value).

Solution

// Initialize the Array
var a = [1,2,3,4,5]

// Get minimum element

var min = a.minElement()

print(min!)

6.20 Get maximum element from array

Problem
I have an array and want to get the maximum element (highest value).

Solution

// Initialize the Array
var a = [1,2,3,4,5]

// Get maximum element

var min = a.maxElement()

print(min!)

59
6.21 Check if array is empty

Problem
I want to check if an Array is empty.

Solution

// Initialize the Array
var a = [1,2,3]

// Check if it is empty

if a.isEmpty {
print("Ooops, it's empty")
}
else {
print("No, it's not empty")
}

6.22 Check if array contains element

Problem
I want to check if an array contains a specific value/element.

Solution

// Initialize the Array
var a = [1,2,3,4,5]

// Check if it contains the number '6'


if a.contains(6) {
print("Yes, it does contain number 6")
}
else {
print("No, it doesn't")
}

60
6.23 Check if 2 arrays are equal

Problem
I have two arrays and want to check if they are equal (if it's the same array, with all ele-
ments in the same order).

Solution

// Initialize the Arrays
let a1 = [1, 2, 3]
let a2 = [2, 3, 1]

// Check if they are the same

if a1==a2 {
print("S1 is the same as S2")
}
else {
print("S1 is not the same as S2")
}

6.24 Concatenate arrays

Problem
I want to concatenate 2 or more arrays.

Solution

// Initialize the first Array
let a = [1,2,3]

// Concatenate them
var b = a + [4,5,6]
print(b)

61
6.25 Insert item at array index

Problem
I have an Array and want to insert a new item at a specifix index position.

Solution

// Initialize the Array
var a = [1,2,3]

// Insert value '6' at index '2'


a.insert(6, atIndex:2)

print(a)

6.26 Swap 2 elements in array

Problem
I have an array and want to swap two of its elements, by index.

Solution

// Initialize the Array
var arr = ["one", "two", "three", "four", "five"]

// Swap elements at index: 2 and 3

swap(&arr[2], &arr[3])
print(arr)

62
6.27 Filter an array based on condition

Problem
I have an array and want to filter its elements based on a defined condition.

Solution

// Initialize the Array
var a = [1,2,3,4,5,6]

// Get only even numbers: X % 2 = 0

a = a.filter { $0 % 2 == 0 }
print(a)

6.28 Join array elements using separator

Problem
I have an array and want to join its elements in a string, using a specific separator.

Solution

// Initialize the Array
var a = ["one", "two", "three"]

// Join array elements


// using ':' as separator

var str = a.joinWithSeparator(":")


print(str)

63
6.29 Map an array to another array

Problem
I have an array and want to map it to a different array, based on a given transformation.

Solution

// Initialize the Array
var a = [1,2,3,4,5,6]

// Map values to their doubles: 1->2, 2->4, etc.

var b = a.map { $0 * 2 }
print(b)

6.30 Pop last item from array

Problem
I have an Array and want to pop (delete and return) its last element.

Solution

// Initialize the Array
var a = [1,2,3]

// Remove last item


let lastItem = a.removeLast()

print(lastItem)
print(a)

64
6.31 Sort array in ascending order

Problem
I have an Array and want to sort it (numeric or lexicographically) in ascending order.

Solution

// Initialize the Array
var a = [6,3,2,1,5,4]

// Sort (ascending) its elements

a = a.sort { $0 < $1 }
print(a)

6.32 Sort array in descending order

Problem
I have an Array and want to sort it (numeric or lexicographically) in descending order.

Solution

// Initialize the Array
var a = [6,3,2,1,5,4]

// Sort (descending) its elements

a = a.sort { $0 > $1 }
print(a)

65
6.33 Reverse an array

Problem
I have an Array and want to reverse it (reverse the order of its contents).

Solution

// Initialize the Array
var a = [1,2,3,4,5,6]

// Reverse its contents

a = a.reverse()
print(a)

66
67
7
“Impossible is a word to be found
Dictionaries only in the dictionary of fools.”

– Napoleon Bonaparte
7.1 Create an empty dictionary

Problem
I want to create/initialize an empty Dictionary.

Solution

// Initialize the Dictionary - Solution A
let d1 = [String:String]()

// Initialize the Dictionary - Solution B


let d2 : [String:String] = [:]

7.2 Create a dictionary with values

Problem
I want to create a new Dictionary and set some keys-values.

Solution

// Initialize the Dictionary
let d = [”username”:”drkameleon”, “email”:”drkameleon@gmail.com”]

print(d)

69
7.3 Add item to dictionary

Problem
I have a Dictionary and want to add a new key-value pair.

Solution

// Initialize the Dictionary
var dict = ["name": "John", "surname": "Doe"]

// Add a new key with a value

dict["email"] = "john.doe@email.com"

print(dict)

7.4 Set dictionary element for key

Problem
I have a Dictionary and want to set a new value to one of its elements, by key.

Solution

// Initialize the Dictionary
var dict = ["name": "John", "surname": "Doe"]

// Set the element with key: 'name' to 'Jane'

dict["name"] = "Jane"

print(dict)

70
7.5 Get dictionary value for key

Problem
I have a Dictionary and want to get a specific value, by key.

Solution

// Initialize the Dictionary
var dict = ["name": "John", "surname": "Doe"]

// Get element for key "name"

print(dict["name"])

7.6 Check if object is a dictionary

Problem
I have an object and want to check if it's a Dictionary object.

Solution

// Initialize the dictionary

let dict = ["name":"John", "surname":"Doe"]

// Check if 'dict' is a Dictionary

if dict is Dictionary {
print("Yes, it's a Dictionary")
}

71
7.7 Get array of keys in dictionary

Problem
I have a dictionary and want to get an array of all its keys.

Solution

// Initialize the Dictionary
let dict = ["name": "John", "surname": "Doe"]

// Get array of keys

var keys = Array(dict.keys)


print(keys)

7.8 Get array of values in dictionary

Problem
I have a dictionary and want to get an array of all its values.

Solution

// Initialize the Dictionary
let dict = ["name": "John", "surname": "Doe"]

// Get array of values

var keys = Array(dict.values)


print(keys)

72
7.9 Remove all items from dictionary

Problem
I want to remove all elements from an existing dictionary.

Solution

// Initialize the Dictionary
var dict = ["name": "John", "surname": "Doe"]

// Remove all elements

dict.removeAll()

print(dict)

7.10 Remove item from dictionary with key

Problem
I have a Dictionary and want to delete an item with a specific key.

Solution

// Initialize the Dictionary
var dict = ["name": "John", "surname": "Doe"]

// Remove item with key 'name'

dict.removeValueForKey("name")
print(dict)

73
7.11 Loop through dictionary

Problem
I have a Dictionary and want to iterate through all of its elements.

Solution

// Initialize the Dictionary
let dict = ["name": "John", "surname": "Doe"]

// Iterate through the dictionary

for (key,value) in dict {


print("\(key) = \(value)")
}

7.12 Get the size of a dictionary

Problem
I have a Dictionary and want to calculate its size/capacity (how many key-value pairs it
contains).

Solution

// Initialize the Dictionary
var dict = ["name": "John", "surname": "Doe"]

// Get the size of the dictionary

let size = dict.count


print(size)

74
7.13 Check if 2 dictionaries are equal

Problem
I have two dictionaries and want to check if they are equal (if it's the same dictionary, with
the exact same key-value pairs).

Solution

// Initialize the Dictionaries
let d1 = ["name": "John", "surname": "Doe"]
let d2 = ["name": "Jane", "surname": "Doe"]

// Check if they are the same

if d1==d2 {
print("D1 is the same as D2")
}
else {
print("D1 is not the same as D2")
}

75
76
8 “A computer would deserve to be
called intelligent if it could deceive

Numbers a human into believing that it was


human.”


– Alan Turing
8.1 Calculate power of a number

Problem
I want to calculate the power of a number: X^Y.

Solution


// Set the number


let n = 4.0

// Get the power n^2


let pwr = pow(n,2)

print(pwr)

8.2 Calculate square root of a number

Problem
I want to calculate the square root of a given number.

Solution


// Set the number


let n = 4.0

// Get the square root


let sq = sqrt(n)

print(sq)

78
8.3 Convert integer to string

Problem
I have an integer and want to convert it to its string equivalent.

Solution


// Integer value
let n = 1986

// Get String value from integer


var s = String(n)
print(s)

8.4 Convert string to integer

Problem
I have a string and want to parse its integer value (if any).

Solution


// String literal
let s = "1986"

// Get Integer value from string


var n = Int(s)

// It's an Optional Int -


// in case the conversion goes wrong
print(n!)// Integer value
let n = 1986

// Get String value from integer


var s = String(n)
print(s)

79
8.5 Convert radians to degrees

Problem
I want to convert radians to degrees.

Solution

// Declare radiansToDegrees function
func radiansToDegrees (radians: Double)->Double {
return radians * 180 / M_PI
}

// Get degrees for radians


var degrees = radiansToDegrees(1)
print(degrees)

8.6 Generate a random number

Problem
I want to generate a random number, between 0 and N-1.

Solution

// Generate a random number
// between 0 and 9 (10-1)

let rand = Int(arc4random_uniform(10))

print(rand)

80
81
9
“Simplicity is prerequisite
Exceptions for reliability.”


– Edsger W. Dijkstra
9.1 Handle exceptions

Problem
I want to handle possible exceptions/errors, using a Do-Catch statement.

Solution

// Let's try reading from a file

do {
let contents = try NSString(contentsOfFile: "myfile.txt",
encoding: NSUTF8StringEncoding)
print(contents)
}
catch let error as NSError {
// Catch a possible error

print("Ooops! Something went wrong: \(error)")


}

83
9.2 Throw and catch exceptions

Problem
I want to create a functions that throws an error and then be able to "catch" it, using a Do-
Catch statement.

Solution

// Declare our error type
enum MyError: ErrorType {
case NumberIsLower
case NumberIsGreater
}

// Declare a function
// that throws an exception
func testFunc(a: Int) throws {
if a<10 {
throw MyError.NumberIsLower
}
else if a>10 {
throw MyError.NumberIsGreater
}
else {
print("Great!")
}
}

// Try calling it
// and catch all possible exceptions
do {
try testFunc(5)
}
catch MyError.NumberIsLower {
print("Ooops! Number was lower than 10")
}
catch MyError.NumberIsGreater {
print("Ooops! Number was greater than 10")
}

84
85
10 “The first principle is that you must
Files not fool yourself and you are the
easiest person to fool.”


– Richard P. Feynman
10.1 Check if file exists

Problem
I want to check if a file/folder exists at a specific location.

Solution

// Create a FileManager instance
let fileManager = NSFileManager.defaultManager()

// Check if file exists, given its path

if fileManager.fileExistsAtPath("hello.swift") {
print("File exists")
} else {
print("File not found")
}

10.2 Check if file is executable

Problem
I want to check if file, at a specific location, is executable.

Solution

// Create a FileManager instance
let fileManager = NSFileManager.defaultManager()

// Check if file exists, given its path

if fileManager.isExecutableFileAtPath("hello.swift") {
print("File is executable")
} else {
print("File is not executable")
}

87
10.3 Check if file is writable

Problem
I want to check if file, at a specific location, is writable.

Solution

// Create a FileManager instance
let fileManager = NSFileManager.defaultManager()

// Check if file exists, given its path

if fileManager.isWritableFileAtPath("hello.swift") {
print("File is writable")
} else {
print("File is read-only")
}

10.4 Copy file to location

Problem
I have a file a want to copy to some specific location.

Solution

// Create a FileManager instance
let fileManager = NSFileManager.defaultManager()

// Copy 'hello.swift' to 'subfolder/hello.swift'

do {
try fileManager.copyItemAtPath("hello.swift", toPath: "subfolder/hello.swift")
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

88
10.5 Create a folder

Problem
I want to create a new directory at a specific location.

Solution

// Create a FileManager instance
let fileManager = NSFileManager.defaultManager()

// Create 'subfolder' directory

do {
try fileManager.createDirectoryAtPath("subfolder",
withIntermediateDirectories: true,
attributes: nil)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

89
10.6 Delete a file/folder

Problem
I want to delete/remove a file or folder at a given location.

Solution

// Create a FileManager instance
let fileManager = NSFileManager.defaultManager()

// Delete 'hello.swift' file

do {
try fileManager.removeItemAtPath("hello.swift")
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

10.7 Get current directory path

Problem
I want to get the current directory path.

Solution

// Create a FileManager instance

let fileManager = NSFileManager.defaultManager()

// Get current directory path

let path = fileManager.currentDirectoryPath


print(path)

90
10.8 Get temporary directory path

Problem
I want to get the path the temporary directory, where I can store my temp files.

Solution

// Get temporary directory path

let path = NSTemporaryDirectory() as String


print(path)

10.9 Get attributes of file

Problem
I want to get the attributes of a files, at given location: creation date, file type, owner, etc.

Solution

// Create a FileManager instance
let fileManager = NSFileManager.defaultManager()

// Get attributes of 'myfile.txt' file

do {
let attributes = try fileManager.attributesOfItemAtPath("myfile.txt")
print(attributes)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

91
10.10 Get directory contents

Problem
I want to get directory contents, at a specific path.

Solution

// Create a FileManager instance
let fileManager = NSFileManager.defaultManager()

// Get contents in directory: '.' (current one)

do {
let files = try fileManager.contentsOfDirectoryAtPath(".")
print(files)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

92
10.11 Move file to different location

Problem
I want to move a file, from its original location, to a different one.

Solution

// Create a FileManager instance
let fileManager = NSFileManager.defaultManager()

// Move 'hello.swift' to 'subfolder/hello.swift'

do {
try fileManager.moveItemAtPath("hello.swift",
toPath: "subfolder/hello.swift")
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

93
10.12 Rename a file

Problem
I have a file and want to rename it.

Solution

// Create a FileManager instance
let fileManager = NSFileManager.defaultManager()

// Rename 'hello.swift' as 'goodbye.swift'

do {
try fileManager.moveItemAtPath("hello.swift",
toPath: "goodbye.swift")
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

94
10.13 Read string from file

Problem
I have a text file and want to read its contents into a String.

Solution

// Set the file path
let path = "myfile.txt"

do {
// Get the contents
let contents = try NSString(contentsOfFile: path,
encoding: NSUTF8StringEncoding)
print(contents)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

95
10.14 Write string to file

Problem
I have a text file and want to read its contents into a String.

Solution

// Set the file path
let path = "myfile.txt"

// Set the contents


let contents = "Here are my file's contents"

do {
// Write contents to file
try contents.writeToFile(path,
atomically: false,
encoding: NSUTF8StringEncoding)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

96
10.15 Read data from file

Problem
I have a file and want to read its data.

Solution

// Create a FileHandle instance

let file: NSFileHandle? = NSFileHandle(forReadingAtPath: "hello.swift")

if file != nil {
// Read all the data
let data = file?.readDataToEndOfFile()

// Close the file


file?.closeFile()

// Convert our data to string


let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(str!)
}
else {
print("Ooops! Something went wrong!")
}

97
10.16 Write data to file

Problem
I have some data and want to write it to a file.

Solution

// Create a FileHandle instance

let file: NSFileHandle? = NSFileHandle(forWritingAtPath: "output.txt")

if file != nil {
// Set the data we want to write
let data = ("Silentium est aureum" as NSString).
dataUsingEncoding(NSUTF8StringEncoding)

// Write it to the file


file?.writeData(data!)

// Close the file


file?.closeFile()
}
else {
print("Ooops! Something went wrong!")
}

98
99
11 “Do not dwell in the past, do not
Date/Time dream of the future, concentrate
the mind on the present moment.”

– Buddha
11.1 Get NSDate for current date

Problem
I want to get the NSDate object for current date/time.

Solution

// Get NSDate for current date
let date = NSDate()

print(date)

11.2 Create NSDate from day/month/year

Problem
I want to create an NSDate object using the values for day, month and year.

Solution

// Initialize Date components
var c = NSDateComponents()
c.year = 2015
c.month = 8
c.day = 31

// Get NSDate given the above date components


var date = NSCalendar(identifier: NSCalendarIdentifierGregorian)?.dateFromComponents(c)

print(date!)

101
11.3 Get Unix timestap for current date

Problem
I want to get the Unix timestamp for current date/time.

Solution

// Get the Unix timestamp
let timestamp = NSDate().timeIntervalSince1970

print(timestamp)

11.4 Get NSDate from string using format

Problem
I have a Date string and want to convert it to an NSDate object, using a specific date for-
mat.

Solution

// Initialize Date string
var dateStr = "2015-08-25"

// Set date format


var dateFmt = NSDateFormatter()
dateFmt.timeZone = NSTimeZone.defaultTimeZone()
dateFmt.dateFormat = "yyyy-MM-dd"

// Get NSDate for the given string


var date = dateFmt.dateFromString(dateStr)

print(date!)

102
11.5 Compare 2 dates

Problem
I have two NSDate objects and want to compare them: see if they are equal, or which one
is earlier/later.

Solution

// Get current date
let dateA = NSDate()

// Get a later date (after a couple of milliseconds)


let dateB = NSDate()

// Compare them
switch dateA.compare(dateB) {
case .OrderedAscending : print("Date A is earlier than date B")
case .OrderedDescending : print("Date A is later than date B")
case .OrderedSame : print("The two dates are the same")
}

103
104
12 “Your pain is the breaking of
Shell the shell that encloses
your understanding.”


– Khalil Gibran
12.1 Get command line arguments

Problem
I want to get the arguments passed to the command line.

Solution

// Loop through the command line arguments
// Process.arguments[0] is the Swift script

for arg in Process.arguments {


print(arg)
}

106
12.2 Execute a shell command

Problem
I want to execute a shell command (as in the terminal) and get its output.

Solution

// Create a Task instance
let task = NSTask()

// Set the task parameters


task.launchPath = "/usr/bin/env"
task.arguments = ["pwd"]

// Create a Pipe and make the task


// put all the output there
let pipe = NSPipe()
task.standardOutput = pipe

// Launch the task


task.launch()

// Get the data


let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = NSString(data: data, encoding: NSUTF8StringEncoding)

print(output!)

107
12.3 Execute a shell task asynchronously

Problem
I want to execute an asynchronous shell task and be able to process both the available
data (sent by the task) and the final output.

Solution

let task = NSTask()

// Set the task parameters


task.launchPath = "/usr/bin/env"
task.arguments = ["ls", "-la"]

// Create a Pipe and make the task


// put all the output there
let pipe = NSPipe()
task.standardOutput = pipe

let outputHandle = pipe.fileHandleForReading


outputHandle.waitForDataInBackgroundAndNotify()

// When new data is available


var dataAvailable : NSObjectProtocol!
dataAvailable =
NSNotificationCenter.defaultCenter().addObserverForName(NSFileHandleDataAvailableNotific
ation,
object: outputHandle, queue: nil) { notification -> Void in
let data = pipe.fileHandleForReading.availableData
if data.length > 0 {
if let str = NSString(data: data, encoding: NSUTF8StringEncoding) {
print("Task sent some data: \(str)")
}
outputHandle.waitForDataInBackgroundAndNotify()
} else {
NSNotificationCenter.defaultCenter().removeObserver(dataAvailable)
}
}

// When task has finished


var dataReady : NSObjectProtocol!

108
dataReady =
NSNotificationCenter.defaultCenter().addObserverForName(NSTaskDidTerminateNotification,
object: pipe.fileHandleForReading, queue: nil) { notification -> Void in
print("Task terminated!")
NSNotificationCenter.defaultCenter().removeObserver(dataReady)
}

// Launch the task


task.launch()

109
110
13 “The sea, once it casts its spell,
Web holds one in its net of wonder
forever.”


– Jacques Yves Cousteau


13.1 Download a webpage

Problem
I want to download the source (HTML) of a specific web page, given its complete URL.

Solution

// Set the page URL we want to download
let URL = NSURL(string: "http://iswift.org")

// Try downloading it
do {
let htmlSource = try String(contentsOfURL: URL!,
encoding: NSUTF8StringEncoding)
print(htmlSource)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

112
13.2 Make an HTTP request

Problem
I want to make a synchronous HTTP request, given a target URL.

Solution

// Set the URL where we're making the request

let request = NSURLRequest(URL: NSURL(string: "http://iswift.org")!)


do {
// Perform the request
var response : AutoreleasingUnsafeMutablePointer<NSURLResponse?> = nil
let data = try NSURLConnection.sendSynchronousRequest(request,
returningResponse: response)

// Get data as string


let str = NSString(data: data,
encoding: NSUTF8StringEncoding)
print(str)
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}

113
13.3 Make an HTTP request asynchronously

Problem
I want to make an asynchronous HTTP request, given a target URL.

Solution

// Set the URL where we're making the request
let request = NSURLRequest(URL: NSURL(string: "http://iswift.org")!)

// Perform the request


NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(),
completionHandler:{
(response: NSURLResponse?, data: NSData?, error: NSError?)-> Void in

// Get data as string


let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(str)
}
);

114
115
X
“This is the end,

Appendix my only friend, the end...”
– The Doors

cxvi
X.1 Standard Swift Library

• abs(x: T) -> T

• alignof(T.Type) -> Int

• alignofValue(T) -> Int

• anyGenerator(base: G) -> AnyGenerator<G.Element>

• anyGenerator(body: () -> Element?() -> Element?) -> AnyGenerator<Element>

• assert(condition: Bool) -> Void

• assert(condition: Bool, message: String) -> Void

• assertionFailure() -> Void

• assertionFailure(message: String) -> Void

• debugPrint(items: Any...) -> Void

• debugPrint(items: Any..., separator: String, terminator: String) -> Void

• debugPrint(items: Any..., separator: String, terminator: String, toStream: &Target) -> Void

• debugPrint(items: Any..., toStream: &Target) -> Void

• dump(x: T) -> T

• dump(x: T, &targetStream: TargetStream) -> T

• dump(x: T, &targetStream: TargetStream, name: String?, indent: Int, maxDepth: Int, max-
Items: Int) -> T

cxvii
• dump(x: T, name: String?, indent: Int, maxDepth: Int, maxItems: Int) -> T

• fatalError() -> Void

• fatalError(message: String) -> Void

• getVaList(args: [CVarArgType]) -> CVaListPointer

• isUniquelyReferenced(&object: T) -> Bool

• isUniquelyReferencedNonObjC(&object: T) -> Bool

• isUniquelyReferencedNonObjC(&object: T?) -> Bool

• max(x: T, y: T) -> T

• max(x: T, y: T, z: T, rest: T...) -> T

• min(x: T, y: T) -> T

• min(x: T, y: T, z: T, rest: T...) -> T

• numericCast(x: T) -> U

• precondition(condition: Bool) -> Void

• precondition(condition: Bool, message: String) -> Void

• preconditionFailure() -> Void

• preconditionFailure(message: String) -> Void

• print(items: Any...) -> Void

• print(items: Any..., separator: String, terminator: String) -> Void

• print(items: Any..., separator: String, terminator: String, toStream: &Target) -> Void

cxviii
• print(items: Any..., toStream: &Target) -> Void

• readLine() -> String?

• readLine(stripNewline: Bool) -> String?

• sizeof(T.Type) -> Int

• sizeofValue(T) -> Int

• strideof(T.Type) -> Int

• strideofValue(T) -> Int

• swap(&a: T, &b: T) -> Void

• transcode(inputEncoding: InputEncoding.Type, outputEncoding: OutputEncoding.Type,


input: Input, output: (OutputEncoding.CodeUnit) -> ()(OutputEncoding.CodeUnit) -> (),
stopOnError: Bool) -> Bool

• unsafeAddressOf(object: AnyObject) -> UnsafePointer<Void>

• unsafeBitCast(x: T, U.Type) -> U

• unsafeDowncast(x: AnyObject) -> T

• unsafeUnwrap(nonEmpty: T?) -> T

• withExtendedLifetime(x: T, f: () throws -> Result() throws -> Result) -> Result

• withExtendedLifetime(x: T, f: T throws -> ResultT throws -> Result) -> Result

• withUnsafeMutablePointer(&arg: T, body: UnsafeMutablePointer<T> throws -> Resul-


tUnsafeMutablePointer<T> throws -> Result) -> Result

• withUnsafeMutablePointers(&arg0: A0, &arg1: A1, &arg2: A2, body: (UnsafeMutable-


Pointer<A0>, UnsafeMutablePointer<A1>, UnsafeMutablePointer<A2>) throws -> Re-

cxix
sult(UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>, UnsafeMutable-
Pointer<A2>) throws -> Result) -> Result

• withUnsafeMutablePointers(&arg0: A0, &arg1: A1, body: (UnsafeMutablePointer<A0>,


UnsafeMutablePointer<A1>) throws -> Result(UnsafeMutablePointer<A0>, UnsafeMuta-
blePointer<A1>) throws -> Result) -> Result

• withUnsafePointer(&arg: T, body: UnsafePointer<T> throws -> ResultUnsafePointer<T>


throws -> Result) -> Result

• withUnsafePointers(&arg0: A0, &arg1: A1, &arg2: A2, body: (UnsafePointer<A0>, Un-


safePointer<A1>, UnsafePointer<A2>) throws -> Result(UnsafePointer<A0>, Unsafe-
Pointer<A1>, UnsafePointer<A2>) throws -> Result) -> Result

• withUnsafePointers(&arg0: A0, &arg1: A1, body: (UnsafePointer<A0>, Unsafe-


Pointer<A1>) throws -> Result(UnsafePointer<A0>, UnsafePointer<A1>) throws -> Re-
sult) -> Result

• withVaList(args: [CVarArgType], f: CVaListPointer -> RCVaListPointer -> R) -> R

• withVaList(builder: VaListBuilder, f: CVaListPointer -> RCVaListPointer -> R) -> R

• zip(sequence1: Sequence1, sequence2: Sequence2) -> Zip2Sequence<Sequence1, Se-


quence2>

cxx
X.2 Strings

• append(c: Character) -> Void

• append(x: UnicodeScalar) -> Void

• appendContentsOf(newElements: S) -> Void

• appendContentsOf(other: String) -> Void

• characters: String.CharacterView

• debugDescription: String

• endIndex: Index

• hashValue: Int

• hasPrefix(prefix: String) -> Bool

• hasSuffix(suffix: String) -> Bool

• insert(newElement: Character, atIndex: Index) -> Void

• insertContentsOf(newElements: S, at: Index) -> Void

• isEmpty: Bool

• lowercaseString: String

• nulTerminatedUTF8: ContiguousArray<CodeUnit>

• removeAll() -> Void

cxxi
• removeAll(keepCapacity: Bool) -> Void

• removeAtIndex(i: Index) -> Character

• removeRange(subRange: Range<Index>) -> Void

• replaceRange(subRange: Range<Index>, with: C) -> Void

• replaceRange(subRange: Range<Index>, with: String) -> Void

• reserveCapacity(n: Int) -> Void

• startIndex: Index

• unicodeScalars: String.UnicodeScalarView

• uppercaseString: String

• utf16: String.UTF16View

• utf8: String.UTF8View

• withCString(f: UnsafePointer<Int8> throws -> ResultUnsafePointer<Int8> throws -> Re-


sult) -> Result

• withMutableCharacters(body: (inout String.CharacterView) -> R(inout


String.CharacterView) -> R) -> R

• write(other: String) -> Void

• writeTo(&target: Target) -> Void

cxxii
X.3 Arrays

• append(newElement: Int) -> Void

• appendContentsOf(newElements: C) -> Void

• appendContentsOf(newElements: S) -> Void

• capacity: Int

• contains(element: Self.Generator.Element) -> Bool

• contains(predicate: (Self.Generator.Element) throws -> Bool(Self.Generator.Element)


throws -> Bool) -> Bool

• count: Int

• debugDescription: String

• description: String

• dropFirst() -> Self.SubSequence

• dropFirst(n: Int) -> Self.SubSequence

• dropFirst(n: Int) -> AnySequence<Self.Generator.Element>

• dropLast() -> Self.SubSequence

• dropLast(n: Int) -> AnySequence<Self.Generator.Element>

• dropLast(n: Int) -> Self.SubSequence

• elementsEqual(other: OtherSequence) -> Bool

cxxiii
• elementsEqual(other: OtherSequence, isEquivalent: (Self.Generator.Element,
Self.Generator.Element) throws -> Bool(Self.Generator.Element, Self.Generator.Element)
throws -> Bool) -> Bool

• endIndex: Int

• enumerate() -> EnumerateSequence<Self>

• filter(includeElement: (Self.Generator.Element) throws -> Bool(Self.Generator.Element)


throws -> Bool) -> [Self.Generator.Element]

• first: Self.Generator.Element?

• flatMap(transform: (Self.Generator.Element) throws -> S(Self.Generator.Element) throws


-> S) -> [S.Generator.Element]

• flatMap(transform: (Self.Generator.Element) throws -> T?(Self.Generator.Element) throws


-> T?) -> [T]

• forEach(body: (Self.Generator.Element) throws -> ()(Self.Generator.Element) throws -> ())


-> Void

• generate() -> IndexingGenerator<Self>

• indexOf(element: Self.Generator.Element) -> Self.Index?

• indexOf(predicate: (Self.Generator.Element) throws -> Bool(Self.Generator.Element)


throws -> Bool) -> Self.Index?

• indices: Range<Self.Index>

• insert(newElement: Int, atIndex: Int) -> Void

• insertContentsOf(newElements: C, at: Self.Index) -> Void

• isEmpty: Bool

cxxiv
• last: Self.Generator.Element?

• lazy: LazyCollection<Self>

• lexicographicalCompare(other: OtherSequence) -> Bool

• lexicographicalCompare(other: OtherSequence, isOrderedBefore:


(Self.Generator.Element, Self.Generator.Element) throws -> Bool(Self.Generator.Element,
Self.Generator.Element) throws -> Bool) -> Bool

• map(transform: (Self.Generator.Element) throws -> T(Self.Generator.Element) throws ->


T) -> [T]

• maxElement() -> Self.Generator.Element?

• maxElement(isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) throws


-> Bool(Self.Generator.Element, Self.Generator.Element) throws -> Bool) ->
Self.Generator.Element?

• minElement() -> Self.Generator.Element?

• minElement(isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) throws


-> Bool(Self.Generator.Element, Self.Generator.Element) throws -> Bool) ->
Self.Generator.Element?

• partition(range: Range<Self.Index>) -> Self.Index

• partition(range: Range<Self.Index>, isOrderedBefore: (Self.Generator.Element,


Self.Generator.Element) -> Bool(Self.Generator.Element, Self.Generator.Element) -> Bool)
-> Self.Index

• popLast() -> Int?

• prefix(maxLength: Int) -> AnySequence<Self.Generator.Element>

• prefix(maxLength: Int) -> Self.SubSequence

cxxv
• prefixThrough(position: Self.Index) -> Self.SubSequence

• prefixUpTo(end: Self.Index) -> Self.SubSequence

• reduce(initial: T, combine: (T, Self.Generator.Element) throws -> T(T,


Self.Generator.Element) throws -> T) -> T

• removeAll() -> Void

• removeAll(keepCapacity: Bool) -> Void

• removeAtIndex(index: Int) -> Int

• removeFirst() -> Self.Generator.Element

• removeFirst(n: Int) -> Void

• removeLast() -> Int

• removeRange(subRange: Range<Self.Index>) -> Void

• replaceRange(subRange: Range<Int>, with: C) -> Void

• reserveCapacity(minimumCapacity: Int) -> Void

• reverse() -> ReverseCollection<Self>

• reverse() -> [Self.Generator.Element]

• reverse() -> ReverseRandomAccessCollection<Self>

• sort() -> [Self.Generator.Element]

• sort(isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) ->


Bool(Self.Generator.Element, Self.Generator.Element) -> Bool) ->
[Self.Generator.Element]

cxxvi
• sortInPlace() -> Void

• sortInPlace(isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) ->


Bool(Self.Generator.Element, Self.Generator.Element) -> Bool) -> Void

• split(isSeparator: (Self.Generator.Element) throws -> Bool(Self.Generator.Element) throws


-> Bool) -> [Self.SubSequence]

• split(isSeparator: (Self.Generator.Element) throws -> Bool(Self.Generator.Element) throws


-> Bool) -> [AnySequence<Self.Generator.Element>]

• split(maxSplit: Int, allowEmptySlices: Bool, isSeparator: (Self.Generator.Element) throws


-> Bool(Self.Generator.Element) throws -> Bool) ->
[AnySequence<Self.Generator.Element>]

• split(maxSplit: Int, allowEmptySlices: Bool, isSeparator: (Self.Generator.Element) throws


-> Bool(Self.Generator.Element) throws -> Bool) -> [Self.SubSequence]

• split(separator: Self.Generator.Element) -> [Self.SubSequence]

• split(separator: Self.Generator.Element) -> [AnySequence<Self.Generator.Element>]

• split(separator: Self.Generator.Element, maxSplit: Int, allowEmptySlices: Bool) ->


[Self.SubSequence]

• split(separator: Self.Generator.Element, maxSplit: Int, allowEmptySlices: Bool) ->


[AnySequence<Self.Generator.Element>]

• startIndex: Int

• startsWith(other: OtherSequence) -> Bool

• startsWith(other: OtherSequence, isEquivalent: (Self.Generator.Element,


Self.Generator.Element) throws -> Bool(Self.Generator.Element, Self.Generator.Element)
throws -> Bool) -> Bool

cxxvii
• suffix(maxLength: Int) -> Self.SubSequence

• suffix(maxLength: Int) -> AnySequence<Self.Generator.Element>

• suffixFrom(start: Self.Index) -> Self.SubSequence

• underestimateCount() -> Int

• withUnsafeBufferPointer(body: (UnsafeBufferPointer<Int>) throws -> R(UnsafeBuffer-


Pointer<Int>) throws -> R) -> R

• withUnsafeMutableBufferPointer(body: (inout UnsafeMutableBufferPointer<Int>)


throws -> R(inout UnsafeMutableBufferPointer<Int>) throws -> R) -> R

cxxviii
X.4 Dictionaries

• contains(predicate: (Self.Generator.Element) throws -> Bool(Self.Generator.Element)


throws -> Bool) -> Bool

• count: Int

• debugDescription: String

• description: String

• dropFirst() -> Self.SubSequence

• dropFirst(n: Int) -> AnySequence<Self.Generator.Element>

• dropFirst(n: Int) -> Self.SubSequence

• dropLast() -> Self.SubSequence

• dropLast(n: Int) -> Self.SubSequence

• dropLast(n: Int) -> AnySequence<Self.Generator.Element>

• elementsEqual(other: OtherSequence, isEquivalent: (Self.Generator.Element,


Self.Generator.Element) throws -> Bool(Self.Generator.Element, Self.Generator.Element)
throws -> Bool) -> Bool

• endIndex: DictionaryIndex<String, String>

• enumerate() -> EnumerateSequence<Self>

• filter(includeElement: (Self.Generator.Element) throws -> Bool(Self.Generator.Element)


throws -> Bool) -> [Self.Generator.Element]

cxxix
• first: Self.Generator.Element?

• flatMap(transform: (Self.Generator.Element) throws -> S(Self.Generator.Element) throws


-> S) -> [S.Generator.Element]

• flatMap(transform: (Self.Generator.Element) throws -> T?(Self.Generator.Element) throws


-> T?) -> [T]

• forEach(body: (Self.Generator.Element) throws -> ()(Self.Generator.Element) throws -> ())


-> Void

• generate() -> DictionaryGenerator<String, String>

• indexForKey(key: String) -> DictionaryIndex<String, String>?

• indexOf(predicate: (Self.Generator.Element) throws -> Bool(Self.Generator.Element)


throws -> Bool) -> Self.Index?

• indices: Range<Self.Index>

• isEmpty: Bool

• keys: LazyMapCollection<Dictionary<String, String>, String>

• lazy: LazyCollection<Self>

• lexicographicalCompare(other: OtherSequence, isOrderedBefore:


(Self.Generator.Element, Self.Generator.Element) throws -> Bool(Self.Generator.Element,
Self.Generator.Element) throws -> Bool) -> Bool

• map(transform: (Self.Generator.Element) throws -> T(Self.Generator.Element) throws ->


T) -> [T]

• maxElement(isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) throws


-> Bool(Self.Generator.Element, Self.Generator.Element) throws -> Bool) ->
Self.Generator.Element?

cxxx
• minElement(isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) throws
-> Bool(Self.Generator.Element, Self.Generator.Element) throws -> Bool) ->
Self.Generator.Element?

• popFirst() -> (String, String)?

• prefix(maxLength: Int) -> Self.SubSequence

• prefix(maxLength: Int) -> AnySequence<Self.Generator.Element>

• prefixThrough(position: Self.Index) -> Self.SubSequence

• prefixUpTo(end: Self.Index) -> Self.SubSequence

• reduce(initial: T, combine: (T, Self.Generator.Element) throws -> T(T,


Self.Generator.Element) throws -> T) -> T

• removeAll() -> Void

• removeAll(keepCapacity: Bool) -> Void

• removeAtIndex(index: DictionaryIndex<String, String>) -> (String, String)

• removeValueForKey(key: String) -> String?

• reverse() -> [Self.Generator.Element]

• sort(isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) ->


Bool(Self.Generator.Element, Self.Generator.Element) -> Bool) ->
[Self.Generator.Element]

• split(isSeparator: (Self.Generator.Element) throws -> Bool(Self.Generator.Element) throws


-> Bool) -> [Self.SubSequence]

• split(isSeparator: (Self.Generator.Element) throws -> Bool(Self.Generator.Element) throws


-> Bool) -> [AnySequence<Self.Generator.Element>]

cxxxi
• split(maxSplit: Int, allowEmptySlices: Bool, isSeparator: (Self.Generator.Element) throws
-> Bool(Self.Generator.Element) throws -> Bool) ->
[AnySequence<Self.Generator.Element>]

• split(maxSplit: Int, allowEmptySlices: Bool, isSeparator: (Self.Generator.Element) throws


-> Bool(Self.Generator.Element) throws -> Bool) -> [Self.SubSequence]

• startIndex: DictionaryIndex<String, String>

• startsWith(other: OtherSequence, isEquivalent: (Self.Generator.Element,


Self.Generator.Element) throws -> Bool(Self.Generator.Element, Self.Generator.Element)
throws -> Bool) -> Bool

• suffix(maxLength: Int) -> AnySequence<Self.Generator.Element>

• suffix(maxLength: Int) -> Self.SubSequence

• suffixFrom(start: Self.Index) -> Self.SubSequence

• underestimateCount() -> Int

• updateValue(value: String, forKey: String) -> String?

• values: LazyMapCollection<Dictionary<String, String>, String>

cxxxii
X.5 Numbers: Int

• advancedBy(n: Distance) -> Int

• advancedBy(n: Self.Distance, limit: Self) -> Self

• bigEndian: Int

• byteSwapped: Int

• description: String

• distanceTo(other: Int) -> Distance

• hashValue: Int

• littleEndian: Int

• predecessor() -> Int

• stride(through: Self, by: Self.Stride) -> StrideThrough<Self>

• stride(to: Self, by: Self.Stride) -> StrideTo<Self>

• successor() -> Int

• toIntMax() -> IntMax

• value: Int64

cxxxiii
X.5 Numbers: Double

• advancedBy(amount: Double) -> Double

• description: String

• distanceTo(other: Double) -> Double

• floatingPointClass: FloatingPointClassification

• hashValue: Int

• isFinite: Bool

• isInfinite: Bool

• isNaN: Bool

• isNormal: Bool

• isSignaling: Bool

• isSignMinus: Bool

• isSubnormal: Bool

• isZero: Bool

• stride(through: Self, by: Self.Stride) -> StrideThrough<Self>

• stride(to: Self, by: Self.Stride) -> StrideTo<Self>

• value: FPIEEE64

cxxxiv
X.6 Booleans

• boolValue: Bool

• description: String

• hashValue: Int

cxxxv
cxxxvi

Você também pode gostar