Escolar Documentos
Profissional Documentos
Cultura Documentos
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
– Francis of Assisi
v
0.1 How to Run Swift
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
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…
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
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.
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)
Executing it
./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
Problem
I want to declare a new constant and assign it a value.
Solution
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
// An Array variable
var d = [1,2,3]
// 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
Problem
I want to create a While loop.
Solution
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
if swiftIsCool {
print("Of course it is!")
}
else {
print("Ooops")
}
Problem
I have a list of different conditions and want to write a Switch-Case statement.
Solution
switch name {
// List the different cases
// - no "break" needed
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
// Call it
myFunc()
Problem
I want to declare a new function, which takes some arguments, and then call it.
Solution
// 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
// Call it
let product = multiply(2, with:5)
print(product)
Problem
I want to declare a function which takes one or more parameters, with default values.
Solution
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
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
return result
}
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
class myClass {
init() {
// Called when a new object is created
print("A new instance was created!")
}
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
class 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
func sayHello() {
print("Hello")
}
}
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
class myClass {
init(prop: String) {
// Called when a new object is created
myProperty = prop
}
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
print(y)
27
3.6 Implement a singleton class
Problem
I want to create a Singleton class.
Solution
class SharedManager {
// Declare our 'sharedInstance' property
static let sharedInstance = SomeManager()
// Set an initializer -
// it will only be called once
init() {
print("SomeManager initialized")
}
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
// Call it
myClosure()
Problem
I want to declare a closure that takes one or more parameters and/or returns some result.
Solution
// 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"
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)
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"
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"
if s is String {
print("Yes, it's a String")
}
Problem
I have a String and want to calculate its length.
Solution
// String literal
let s = "Hello world"
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"
if s.rangeOfString("Hello") != nil {
print("Yes it contains 'Hello'")
}
Problem
I want to check if a string contains a specific regular expression.
Solution
// String literal
let s = "Hello World"
38
5.9 Check if string has prefix
Problem
Check if string has a given prefix.
Solution
// String literal
var a = "Hello World!"
if a.hasPrefix("Hell") {
print("Yes, there is")
}
Problem
Check if string has a given suffix.
Solution
// String literal
var a = "Hello World!"
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")
}
Problem
I have a string and I want to embed variable values within this string.
Solution
// String literal
var username = "John"
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!"
Problem
I want to convert a string to uppercase.
Solution
// String literal
var a = "Hello World!"
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"
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"
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"
str.characters.forEach {
print($0)
}
Problem
I have a string and want to retrieve a substring found within a specific range.
Solution
// String literal
let s = "Hello World"
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"
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"
45
5.21 Repeat a string
Problem
I want to repeat a string several times.
Solution
// String literal
var s : 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! "
s = s.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
print(s)
Problem
I want to create a random UUID (unique identifier string).
Solution
// Create the Unique Identifier
47
48
6
“Great things are done by a series
Arrays of small things brought together.”
Problem
I want to create/initialize an empty Array.
Solution
// Initialize the Array - Solution A
let a1 = [Int]()
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]
print(a)
Problem
I want to append an Array to another Array.
Solution
// Initialize the Array
var a = [1,2,3]
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"]
print(arr)
Problem
I have an array and want to a get a specific element, by index.
Solution
// Initialize the Array
var arr = ["one", "two", "three"]
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"]
Problem
I want to get the last element of an Array.
Solution
// Initialize the Array
let arr = ["one", "two", "three"]
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
if arr is Array {
print("Yes, it's an Array")
}
Problem
I want to remove all elements from an existing array.
Solution
// Initialize the Array
var a = [1,2,3]
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]
print(a)
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"]
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)
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]
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"]
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"]
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]
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"]
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]
print(min!)
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]
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")
}
Problem
I want to check if an array contains a specific value/element.
Solution
// Initialize the Array
var a = [1,2,3,4,5]
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]
if a1==a2 {
print("S1 is the same as S2")
}
else {
print("S1 is not the same as S2")
}
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]
print(a)
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(&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]
a = a.filter { $0 % 2 == 0 }
print(a)
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"]
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]
var b = a.map { $0 * 2 }
print(b)
Problem
I have an Array and want to pop (delete and return) its last element.
Solution
// Initialize the Array
var a = [1,2,3]
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]
a = a.sort { $0 < $1 }
print(a)
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]
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]
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]()
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"]
dict["email"] = "john.doe@email.com"
print(dict)
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"]
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"]
print(dict["name"])
Problem
I have an object and want to check if it's a Dictionary object.
Solution
// Initialize the 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"]
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"]
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"]
dict.removeAll()
print(dict)
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"]
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"]
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"]
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"]
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
– Alan Turing
8.1 Calculate power of a number
Problem
I want to calculate the power of a number: X^Y.
Solution
print(pwr)
Problem
I want to calculate the square root of a given number.
Solution
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
Problem
I have a string and want to parse its integer value (if any).
Solution
// String literal
let s = "1986"
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
}
Problem
I want to generate a random number, between 0 and N-1.
Solution
// Generate a random number
// between 0 and 9 (10-1)
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
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()
if fileManager.fileExistsAtPath("hello.swift") {
print("File exists")
} else {
print("File not found")
}
Problem
I want to check if file, at a specific location, is executable.
Solution
// Create a FileManager instance
let fileManager = NSFileManager.defaultManager()
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()
if fileManager.isWritableFileAtPath("hello.swift") {
print("File is writable")
} else {
print("File is read-only")
}
Problem
I have a file a want to copy to some specific location.
Solution
// Create a FileManager instance
let fileManager = NSFileManager.defaultManager()
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()
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()
do {
try fileManager.removeItemAtPath("hello.swift")
}
catch let error as NSError {
print("Ooops! Something went wrong: \(error)")
}
Problem
I want to get the current directory path.
Solution
// Create a FileManager instance
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
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()
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()
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()
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()
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"
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
if file != nil {
// Read all the data
let data = file?.readDataToEndOfFile()
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
if file != nil {
// Set the data we want to write
let data = ("Silentium est aureum" as NSString).
dataUsingEncoding(NSUTF8StringEncoding)
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)
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
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)
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"
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()
// 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
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()
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()
108
dataReady =
NSNotificationCenter.defaultCenter().addObserverForName(NSTaskDidTerminateNotification,
object: pipe.fileHandleForReading, queue: nil) { notification -> Void in
print("Task terminated!")
NSNotificationCenter.defaultCenter().removeObserver(dataReady)
}
109
110
13 “The sea, once it casts its spell,
Web holds one in its net of wonder
forever.”
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
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")!)
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
• debugPrint(items: Any..., separator: String, terminator: String, toStream: &Target) -> Void
• dump(x: T) -> 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
• max(x: T, y: T) -> T
• min(x: T, y: T) -> T
• numericCast(x: T) -> U
• print(items: Any..., separator: String, terminator: String, toStream: &Target) -> Void
cxviii
• print(items: Any..., toStream: &Target) -> Void
cxix
sult(UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>, UnsafeMutable-
Pointer<A2>) throws -> Result) -> Result
cxx
X.2 Strings
• characters: String.CharacterView
• debugDescription: String
• endIndex: Index
• hashValue: Int
• isEmpty: Bool
• lowercaseString: String
• nulTerminatedUTF8: ContiguousArray<CodeUnit>
cxxi
• removeAll(keepCapacity: Bool) -> Void
• startIndex: Index
• unicodeScalars: String.UnicodeScalarView
• uppercaseString: String
• utf16: String.UTF16View
• utf8: String.UTF8View
cxxii
X.3 Arrays
• capacity: Int
• count: Int
• debugDescription: String
• description: String
cxxiii
• elementsEqual(other: OtherSequence, isEquivalent: (Self.Generator.Element,
Self.Generator.Element) throws -> Bool(Self.Generator.Element, Self.Generator.Element)
throws -> Bool) -> Bool
• endIndex: Int
• first: Self.Generator.Element?
• indices: Range<Self.Index>
• isEmpty: Bool
cxxiv
• last: Self.Generator.Element?
• lazy: LazyCollection<Self>
cxxv
• prefixThrough(position: Self.Index) -> Self.SubSequence
cxxvi
• sortInPlace() -> Void
• startIndex: Int
cxxvii
• suffix(maxLength: Int) -> Self.SubSequence
cxxviii
X.4 Dictionaries
• count: Int
• debugDescription: String
• description: String
cxxix
• first: Self.Generator.Element?
• indices: Range<Self.Index>
• isEmpty: Bool
• lazy: LazyCollection<Self>
cxxx
• minElement(isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) throws
-> Bool(Self.Generator.Element, Self.Generator.Element) throws -> Bool) ->
Self.Generator.Element?
cxxxi
• split(maxSplit: Int, allowEmptySlices: Bool, isSeparator: (Self.Generator.Element) throws
-> Bool(Self.Generator.Element) throws -> Bool) ->
[AnySequence<Self.Generator.Element>]
cxxxii
X.5 Numbers: Int
• bigEndian: Int
• byteSwapped: Int
• description: String
• hashValue: Int
• littleEndian: Int
• value: Int64
cxxxiii
X.5 Numbers: Double
• description: String
• floatingPointClass: FloatingPointClassification
• hashValue: Int
• isFinite: Bool
• isInfinite: Bool
• isNaN: Bool
• isNormal: Bool
• isSignaling: Bool
• isSignMinus: Bool
• isSubnormal: Bool
• isZero: Bool
• value: FPIEEE64
cxxxiv
X.6 Booleans
• boolValue: Bool
• description: String
• hashValue: Int
cxxxv
cxxxvi