155
Develop on iOS Swift Lab Test www.SwiftLabTest.com Youku By Bruno Delb www.weibo.com/brunodelb i.youku.com/brunodelb | www.weibo.com/brunodelb | blog.delb.cn http://i.youku.com/brunoparis Weibo Official site Introduction to Swift Watch on Youtube ! Watch on Youku !

Introduction to Swift (tutorial)

Embed Size (px)

Citation preview

Page 1: Introduction to Swift (tutorial)

Develop on iOSSwift Lab Test

www.SwiftLabTest.com

Yo

uku

By Bruno Delb

www.weibo.com/brunodelb

i.youku.com/brunodelb | www.weibo.com/brunodelb | blog.delb.cn

http://i.youku.com/brunoparis

We

ibo

Off

icia

l sit

e

Introduction to Swift

Watch on Youtube !

Watch on Youku !

Page 2: Introduction to Swift (tutorial)

THE VARIABLES

Watch on Youtube !

Watch on Youku !

Page 3: Introduction to Swift (tutorial)

• In this lesson, you will learn to use the variables in Swift.

• The semicolons (;) aren't mandatory at the end of each instruction. However, you can write several instructions on a same line. In this case, the ";" will be mandatory to separate the instructions.

Page 4: Introduction to Swift (tutorial)

• To create a constant, it means a variable

whose the value can't be changed, use

"let".

let city = "Paris"

Page 5: Introduction to Swift (tutorial)

• To display the value of the variable "department", simply enter the name of the variable.var department = 74

Department

• Give the value 75 to the variable department.department = 75

Page 6: Introduction to Swift (tutorial)

• It's possible to declare several variables

on a same line and to give them a value.

var city1 = "Paris", city2 =

"Marseille"

• Enter "city1" to display its value.

city1

Page 7: Introduction to Swift (tutorial)

• To declare a variable of type String, add ": String".var city3: String

• Then you can give a value.city3 = "Paris"

• Control its value.city3

Page 8: Introduction to Swift (tutorial)

THE COMMENTS

Watch on Youtube !

Watch on Youku !

Page 9: Introduction to Swift (tutorial)

• In this lesson, you will learn the comments

in Swift.

Page 10: Introduction to Swift (tutorial)

• To add a comment on one line, insert "//"

in front of the comment.

// Comment on one line

Page 11: Introduction to Swift (tutorial)

• To add a comment on several lines, use /*

to start the comment, */ to finish it.

/*

Comment on

several lines

*/

Page 12: Introduction to Swift (tutorial)

• It's possible to create a comment inside another comment. Useful to comment several lines of code including already a comment./*

Comment on

several lines

/* and nested

comments */

*/

Page 13: Introduction to Swift (tutorial)

THE INTEGERS

Watch on Youtube !

Watch on Youku !

Page 14: Introduction to Swift (tutorial)

• In this lesson, you will learn integers in

Swift.

Page 15: Introduction to Swift (tutorial)

• To declare a variable of type integer, add ":

Int" after the name of the variable.

• To create a signed integer, it means able

to receive a positive or negative value,

proceed like this.

var my_int: Int

Page 16: Introduction to Swift (tutorial)

• Give the value -10 to the variable my_int2, of type unsigned integer.my_int = -10

• You can create a variable of type integer but not signed, it means it accepts only positive numbers.var my_int2:UInt

• Give the value 10 to the variable my_int2.my_int2 = 10

Page 17: Introduction to Swift (tutorial)

• There are several types of integers, depending on the capacity.// Signed integers :

var i1: Int8

var i2: Int16

var i3: Int32

var i4: Int64

Page 18: Introduction to Swift (tutorial)

• There are too the equivalents types for the unsigned integers.// Unsigned integers :

var u1: UInt8

var u2: UInt16

var u3: UInt32

var u4: UInt64

u4 = 3

Page 19: Introduction to Swift (tutorial)

THE FLOATS AND THE BIG

VALUES

Watch on Youtube !

Watch on Youku !

Page 20: Introduction to Swift (tutorial)

• In this lesson, you will learn to use the

float numbers and big values in Swift.

Page 21: Introduction to Swift (tutorial)

• To declare a float variable, add a suffix ":

Float" to the name of the variable.

var my_float: Float

• To give a value, it's as usual.

my_float = 1.5

Page 22: Introduction to Swift (tutorial)

• Now, we are going to discover a specific notation for variables with big values.

• Create a variable big_value1 with the value 1000000.var big_value1 = 1000000

• Create a second variable with the same value, but use "_" as separator for thousands.var big_value2 = 1_000_000

• The both values are the same ! To use "_" allows to improve the readability of big values. Verify the two variables are the same by using "==".big_value1 == big_value2

Page 23: Introduction to Swift (tutorial)

THE CONVERSION OF TYPE

Watch on Youtube !

Watch on Youku !

Page 24: Introduction to Swift (tutorial)

• In this lesson, you will study the

conversions of type in Swift.

Page 25: Introduction to Swift (tutorial)

• To convert a string (here "75"), use toInt().var department = "75".toInt()

• To know if the conversion succeeded, just test the variable.if department {

}

• If the conversion fails, like here, department has the value "nil".department = "abc".toInt()

Page 26: Introduction to Swift (tutorial)

• Declare two variables : the first one an integer number, the second one a decimal.var var_int = 1

var var_double = 1.5

• To convert an integer into a decimal (Double), use Double().var new_double = Double(var_int) * var_double

• To convert a Double number into integer, use Int().var new_int = var_int * Int(var_double)

Page 27: Introduction to Swift (tutorial)

THE ATTRIBUTION

Watch on Youtube !

Watch on Youku !

Page 28: Introduction to Swift (tutorial)

• In this lesson, you will learn the attribution

of value in Swift.

Page 29: Introduction to Swift (tutorial)

• Declare a variable "city".var city = "Paris"

• Give the value "Marseille" to this variable.city = "Marseille"

• Test if the value of the variable city is "Paris".if city == "Paris" {

}

Page 30: Introduction to Swift (tutorial)

• If you want to destroy a variable, you have to use "nil".

• However, beforehand, you have to declare the variable with a "?" after the type : var department: int?var department: Int?

• Now, give the value (75 for example) then give the value nil.department = 75

department = nil

Page 31: Introduction to Swift (tutorial)

• Now, let's see the assertions. It's a

assumption. If the condition in first parameter

is not fulfilled, the message in second

position is displayed and the script stops.

var department2 = 75

assert (department > 0, "Department

must be > 0")

Page 32: Introduction to Swift (tutorial)

THE ARITHMETIC

OPERATORS

Watch on Youtube !

Watch on Youku !

Page 33: Introduction to Swift (tutorial)

• In this lesson, you will learn to use the

arithmetic operators in Swift.

Page 34: Introduction to Swift (tutorial)

• To increment a variable, use "+".var my_int = 1 + 1

• To decrement a variable, use "-".my_int = 3 – 1

• To do a multiplication, use "*".my_int = 2 * 3

• To do a division, use "/".my_int = 5 / 2

Page 35: Introduction to Swift (tutorial)

• To concatenate two strings, use "+".

var my_string = "Hello"

my_string = "Hello" + "world"

Page 36: Introduction to Swift (tutorial)

• To get the remainder of a division, use

"%".

var my_int2 = 3%2

Page 37: Introduction to Swift (tutorial)

• There a two others ways to do increments. With "my_int3++", returns the value of the variable then increment. With "++my_int3", increment the value then return the value of the variable.var my_int3 = 0

my_int3 = my_int3 + 1

my_int3++

++my_int3

Page 38: Introduction to Swift (tutorial)

• There are two others ways to do decrements. With "my_int3--", return the value of the variable then decrement. With "--my_int3", decrement the value then return the value of the variable. </source>my_int3 = my_int3 - 1

my_int3--

--my_int3

Page 39: Introduction to Swift (tutorial)

• At last, it's possible do use a simplified

syntax for incrementint (or any other

arithmetic operation). Here, read "my_int4

= my_int4 + 2".

var my_int4 = 1

my_int4 += 2

Page 40: Introduction to Swift (tutorial)

THE COMPARISION

Watch on Youtube !

Watch on Youku !

Page 41: Introduction to Swift (tutorial)

• In this lesson, you will learn to use the

comparision in Swift.

Page 42: Introduction to Swift (tutorial)

• Declare two variables i and j.var i = 3

var j = 3

• "==" return true if the variables are equals.i == j

• "!=" return true if they are differentes.i != j

Page 43: Introduction to Swift (tutorial)

• “>" return true if the first one is greater than the second one.i > j

• “<" return true if the first one is less than the second one.i < j

• “>=" return true if the first one is greater or equal to the second one.i >= j

• “<=" return true if the first one is less or equal to the second one.i <= j

Page 44: Introduction to Swift (tutorial)

• "===" return if the two objects (here

variables) refer to the same instance.

i === j

• "!==" return true if they are differents.

i !== j

Page 45: Introduction to Swift (tutorial)

• Create a variable city with the value "Paris" and test its value in a "if".var city = "Paris"

city == "Paris“

if city == "Paris" {

"Paris !"

}

Page 46: Introduction to Swift (tutorial)

• Now, let's see another useful notation : the conditional ternary operator ("... ? ... : ..."). If the first block ("capital") equals true, then the result is the second block ("Paris"), else the third block ("Marseille").var capital = true

var city2 = capital ? "Paris" :

"Marseille"

Page 47: Introduction to Swift (tutorial)

• To combine the conditions, use "&&" to express the logical "and".var department = 75

var city3 = "Paris"

if department == 6 && city3 != "Marseille" {

"City of the department 6, but not Marseille"

}

Page 48: Introduction to Swift (tutorial)

• To express the logical "or", use "||".if department == 6 || department == 69 {

"City in the department 6 or in the department 69"

}

if department == 75 || department == 74 {

"City in the department 75 or in the department 74"

}

Page 49: Introduction to Swift (tutorial)

THE STRINGS (STRINGS)

Watch on Youtube !

Watch on Youku !

Page 50: Introduction to Swift (tutorial)

• In this lesson, you will learn to use the

strings in Swift.

Page 51: Introduction to Swift (tutorial)

• Declare a variable gender of type Character.var gender: Character

• Declare a variable name of type String.var name: String

• Give the value "M" to the variable gender.gender = "M"

• Give the value "paul" to the variable name.name = "paul"

Page 52: Introduction to Swift (tutorial)

• To use quotations (") in a string, use the

escape character \.

var my_string = "Hello"

var my_string2 = "Hello \"Paul\""

Page 53: Introduction to Swift (tutorial)

• You can integrate the value of a variable in

a string. For this, enclose the variable with

"\(" and ")".

var my_string3 = "Hello \(name)"

Page 54: Introduction to Swift (tutorial)

• To create an empty string, use "". To test if

the string is empty, you can use isEmpty.

var city = ""

if city.isEmpty {

"Empty !"

}

Page 55: Introduction to Swift (tutorial)

• Another way to create an empty string is to

give the value String().

var city2 = String()

if city2.isEmpty {

"Empty !"

}

Page 56: Introduction to Swift (tutorial)

THE HANDLING OF STRINGS

(STRINGS)

Watch on Youtube !

Watch on Youku !

Page 57: Introduction to Swift (tutorial)

• In this lesson, you will learn to handle

strings in Swift.

Page 58: Introduction to Swift (tutorial)

• Create a variable city_with_error of type String.var city_with_error = "Pari"

• Declare a variable suffix of type Character.var suffix: Character = "s"

• To concatenate these two variables, use "+".var city = city_with_error + suffix

Page 59: Introduction to Swift (tutorial)

• To know the length of a string, use the

method countElements.

countElements(city)

for my_char in city {

my_char

}

Page 60: Introduction to Swift (tutorial)

• To compare two strings, use "==".

var city1 = "Paris"

var city2 = "Marseille"

if city1 == city2 {

"The same city !"

}

Page 61: Introduction to Swift (tutorial)

• To know if a string starts with a substring

(here "P"), use the method hasPrefix().

if city1.hasPrefix("P") {

"The first city starts with P

!"

}

Page 62: Introduction to Swift (tutorial)

• To know if a string ends with a substring

(here "s"), use the method hasSuffix().

if city1.hasSuffix("s") {

"The first city ends with s !"

}

Page 63: Introduction to Swift (tutorial)

• To convert in uppercase a string, use

uppercaseString.

city1.uppercaseString

Page 64: Introduction to Swift (tutorial)

• To convert in lowercase a string, use

lowercaseString.

city1.lowercaseString

city1

Page 65: Introduction to Swift (tutorial)

THE ARRAYS

Watch on Youtube !

Watch on Youku !

Page 66: Introduction to Swift (tutorial)

• In this lesson, you will learn the arrays in

Swift.

Page 67: Introduction to Swift (tutorial)

• You have the choice between three

syntaxes to create an array.

var cities: Array<String>

var cities_1: String[]

var cities_2 = String[]()

Page 68: Introduction to Swift (tutorial)

• Create an array cities containing a list of

city names.

cities = ["Paris", "Lille", "Lyon"]

• Create a second array containing the

departments of these cities.

var department = [75, 59, 69]

Page 69: Introduction to Swift (tutorial)

• In order to get the number of items in an

array, use the property count.

cities.count

Page 70: Introduction to Swift (tutorial)

• In order to know is a variable is empty, use

the property isEmpty.

if !cities.isEmpty {

println ("Not empty !")

}

Page 71: Introduction to Swift (tutorial)

• To add an item to an array, use the method

append().

cities.append ("Toulouse")

println (cities)

Page 72: Introduction to Swift (tutorial)

• It's possible to add in one time several

items to an array. For this, use "+="

followed by an array containing the items

to add.

cities += ["Cannes", "Strasbourg"]

println (cities)

Page 73: Introduction to Swift (tutorial)

• To display the value of an item of the array

(0 here, it's the first item of the array), use

[].

cities [0]

Page 74: Introduction to Swift (tutorial)

• To modify an item of the array, proceed as

below.

cities [0] = "Nantes“

println (cities)

Page 75: Introduction to Swift (tutorial)

• You can modify in one time several items.

Here, we modify the items of index 1 to 3.

cities [1...3] = ["x", "y", "z"]

println (cities)

Page 76: Introduction to Swift (tutorial)

• To get a sub-array, ie an array containing a

suitof items from another array, use : [ .. ].

cities [1..3]

Page 77: Introduction to Swift (tutorial)

• To get the index of the last item, use endIndex. To extract the items from an index (here 1) to the end of an array, proceed as below. Attention, the result doesn't include the last item indexed (endIndex).cities [1..cities.endIndex]

Page 78: Introduction to Swift (tutorial)

• You can create a new array from a set of

items from another array.

Array (cities [1..3])

Page 79: Introduction to Swift (tutorial)

• To insert an item in an array, use the

method insert().

cities.insert("a", atIndex: 1)

println (cities)

Page 80: Introduction to Swift (tutorial)

• To remove an item from an array, use the

method removeAtIndex().

cities.removeAtIndex(0)

println (cities)

Page 81: Introduction to Swift (tutorial)

• To remove the last item from an array, use

the method removeLast().

cities.removeLast()

println (cities)

Page 82: Introduction to Swift (tutorial)

• You can too browse the list of the items of

an array by geting the index (the key) and

the value.

for city in cities {

println ("City : \(city)")

}

Page 83: Introduction to Swift (tutorial)

• To display the items of an array and their index in the array, use the loop : for (index, value) in enumerate ...for (index, city) in enumerate

(cities) {

println ("City \(index) ;

\(city)")

}

Page 84: Introduction to Swift (tutorial)

• You can create an array of a predefined

size (5 items here) with the same value

("Paris" here).

cities = Array(count: 5,

repeatedValue: "Paris")

println (cities)

Page 85: Introduction to Swift (tutorial)

• To merge two arrays, simply use the concatenation with "+".var cities1 = ["Paris",

"Marseille"]

var cities2 = ["Lyon", "Lille"]

cities = cities1 + cities2

println (cities)

Page 86: Introduction to Swift (tutorial)

THE DICTIONNARIES

Watch on Youtube !

Watch on Youku !

Page 87: Introduction to Swift (tutorial)

• In this lesson, you will study the

dictionnaries in Swift.

Page 88: Introduction to Swift (tutorial)

• Declare a variable cities2 of type Dictionary, with as key a String and as value an Int.var cities2: Dictionary<String, Int>

• Declare a dictionnary with the syntax ["key": value].var cities = ["Paris": 75, "Lille": 59]

println (cities)

Page 89: Introduction to Swift (tutorial)

• To change an item of the dictionnary,

specify the key between [] and attribute

the value.

cities ["Lyon"] = 69

println (cities)

Page 90: Introduction to Swift (tutorial)

• To modify an item of the dictionary, you can use the method updateValue. The first parameter is the value of the item, the second one is the key.cities.updateValue(6, forKey:

"Marseille")

println (cities)

Page 91: Introduction to Swift (tutorial)

• You can create an array from an entry of a

dictionnary.

var department = cities

["Marseille"]

println (department)

Page 92: Introduction to Swift (tutorial)

• To remove an entry from a dictionnary, you

can attribute the value nil.

cities ["Marseille"] = nil

println (cities)

Page 93: Introduction to Swift (tutorial)

• Here you are another way to remove an

item from the array : the method

removeValueForKey (key).

cities.removeValueForKey("Lyon")

println (cities)

Page 94: Introduction to Swift (tutorial)

• To browse the key and the value of items of a dictionnary, you can use a loop for ... in.for (city, department) in cities {

println ("City \(city) :

department \(department)")

}

Page 95: Introduction to Swift (tutorial)

• You can too browse the list of the keys of

the items of the dictionnary with a for ... in.

for city in cities.keys {

println ("City \(city)")

}

Page 96: Introduction to Swift (tutorial)

• Or browse the values of the items of the dictionnary.for city in cities.values {

println ("City \(city)")

}

var names = Array (cities.keys)

println (names)

Page 97: Introduction to Swift (tutorial)

• To create an empty dictionnary, proceed like this :var cities = Dictionary<String, Int>

• To clean a dictionnary, you can attribute the value [:].cities = [:]

println (cities)

Page 98: Introduction to Swift (tutorial)

PROTOCOLS

Watch on Youtube !

Watch on Youku !

Page 99: Introduction to Swift (tutorial)

• In this lesson, you will study the protocols

in Swift.

Page 100: Introduction to Swift (tutorial)

• Create a protocol CityName with the

property theName.

protocol CityName {

var theName: String { get }

}

Page 101: Introduction to Swift (tutorial)

• Create a structure of type CityName and

implement the property theName.

struct City: CityName {

var theName: String

}

Page 102: Introduction to Swift (tutorial)

• Declare a constant parisName of type City

and give the value "Paris" to the property

theName.

let parisName = City (theName:

"Paris")

Page 103: Introduction to Swift (tutorial)

• Create a class CityObject of type CityName. It implements two properties : name and department, a constructor and the getter of the property theName.class CityObject: CityName {

• Add two properties : : department and name.var department: Int

var name: String

Page 104: Introduction to Swift (tutorial)

• Add a constructor which receives in parameter the name of the ctyand its department.

init (name: String, department: Int) {

self.name = name

self.department = department

}

• You have to declare the getter of the property theName. Make it return the concatenation of name, of " " and of department.

var theName: String {

return name + " " + String (department)

}

}

Page 105: Introduction to Swift (tutorial)

• Declare a variable paris of type CityObject.

The property theName will have the value

"Paris 75".

var paris = CityObject (name:

"Paris", department: 75)

println (paris)

Page 106: Introduction to Swift (tutorial)

THE GENETIC FUNCTIONS

Watch on Youtube !

Watch on Youku !

Page 107: Introduction to Swift (tutorial)

• In this lesson, you will study the generic

functions in Swift.

Page 108: Introduction to Swift (tutorial)

• Create a generic function "swapIt". It will permute two variables of any type.

• "inout" shows that the modifications on the values of the variables will be passed to the variables used for the call.func swapIt<T>(inout a: T, inout b: T) {

• We simply permute the variables a and b.let temp = a

a = b

b = temp

}

Page 109: Introduction to Swift (tutorial)

• Let's call this generic function with two variables x and y of type integer.

• Before the call, x and y have respectively the value 3 and 4. After, their value is 4 and 3.var x = 3

var y = 4

println (x)

println (y)

Page 110: Introduction to Swift (tutorial)

• The "&" shows that these variables used

for the call (x and y) will receive the values

of the variables local to the function.

swapIt (&x, &y)

println (x)

println (y)

Page 111: Introduction to Swift (tutorial)

THE GENERIC TYPES

Watch on Youtube !

Watch on Youku !

Page 112: Introduction to Swift (tutorial)

• In this lesson, you will study the generic

types in Swift.

Page 113: Introduction to Swift (tutorial)

• Create a generic type : Stack. It's a stack.

• Its shows that Stack will receive any type. <T> is the chosen type.struct Stack<T> {

• This array will store the items.var elements = T[]()

• The method push add a record to the array.mutating func push(element: T) {

elements.append(element)

}

• The method pop returns the last value added to the stack and removes this item from the array.

mutating func pop() -> T {

return elements.removeLast()

}

}

Page 114: Introduction to Swift (tutorial)

• Declare a variable items of type Stack of Strings.var items: Stack<String> = Stack<String>()

Items

• Add "Paris" to the stack.items.push ("Paris")

Items

• Add "Marseille" to the stack.items.push ("Marseille")

Items

• Remove the last item of the stack and display it.items.pop()

items

Page 115: Introduction to Swift (tutorial)

THE LOOPS

Watch on Youtube !

Watch on Youku !

Page 116: Introduction to Swift (tutorial)

• In this lesson, you will study the loops in

Swift.

Page 117: Introduction to Swift (tutorial)

• You can create a loop on an array and

read the value of each item.

• Create an array of Strings.

let citiesConstants = ["Paris": 75,

"Lille": 59]

Page 118: Introduction to Swift (tutorial)

• You can too create a loop on an array and

read the key of each item of the array.

for value in citiesConstants {

println (value)

}

Page 119: Introduction to Swift (tutorial)

• Or you can create a loop on an interval of values.var cities = ["Paris": 75, "Lille": 59]

for (key, value) in cities {

println ("\(key) = \(value)")

}

for i in -1..1 {

println (i)

}

Page 120: Introduction to Swift (tutorial)

• The loop while has two versions. The first one is under the form : while … {}. var i = 1

while i < 10 {

println ("Loop \(i)")

i++

}

Page 121: Introduction to Swift (tutorial)

• The second one is under the form : do {} while condition.var j = 1

do {

println ("Loop \(j)")

j++

} while j < 10

Page 122: Introduction to Swift (tutorial)

• The switch is available. It's possible to integrate a condition ("where") in one case. The "default" is mandatory.let city = "Paris"

switch city {

case "Paris":

let comment = "In the department 75"

case "Marseille":

let comment = "In the department 6"

case let theCity where theCity.hasSuffix("s"):

let comment = "The city \(city) finishes by s"

default:

let comment = "What ?"

}

Page 123: Introduction to Swift (tutorial)

• In the first case, we keep the cities in the department 75.case (.Some (let cityName as NSString),

.Some (let cityDepartment as NSNumber))

where cityDepartment == 75:

println ("City \(cityName) : department \(cityDepartment)")

default:

println ("Not found")

}

Page 124: Introduction to Swift (tutorial)

THE FUNCTIONS

Watch on Youtube !

Watch on Youku !

Page 125: Introduction to Swift (tutorial)

• In this lesson, you will learn to use the

functions in Swift.

Page 126: Introduction to Swift (tutorial)

• Create a function hello adding "Hello " at the beginning of the string provided in parameter.

• “name: String” is the input parameter.

• It returns a type String (“-> String”).func hello (name: String) -> String {

• return allows to specify the result of the function.return "Hello \(name)"

}

Page 127: Introduction to Swift (tutorial)

• To call the function, enter the name of the

method followed by parameters between

parentheses.

hello ("John")

Page 128: Introduction to Swift (tutorial)

• A function can return a tuple of values (here the city name and its department).func getParis() -> (String, Int) {

return ("Paris", 75)

}

getParis()

Page 129: Introduction to Swift (tutorial)

• A function can receive a variable number of

arguments. For this, add "..." to the type.

func setCities (cities: String...) {

}

setCities ("Paris", "Marseille",

"Lille")

Page 130: Introduction to Swift (tutorial)

• A function can itself contain a function.func getHelloWorld() -> String {

var text = "Hello"

func addWorld() {

text += "world"

}

addWorld()

return text

}

println (getHelloWorld())

Page 131: Introduction to Swift (tutorial)

THE CLASSES

Watch on Youtube !

Watch on Youku !

Page 132: Introduction to Swift (tutorial)

• In this lesson, you will learn to use the

classes in Swift.

Page 133: Introduction to Swift (tutorial)

• Create a class MyBasicClass with a constructor (init) and a function (myFunction).class MyBasicClass {

init() {

println ("Init")

}

func myFunction() {

println ("Call of myFunction")

}

}

Page 134: Introduction to Swift (tutorial)

• Declare a variable theClass of type

MyBasicClass. Instantiate the class then

call its function myFunction().

var theClass: MyBasicClass

Page 135: Introduction to Swift (tutorial)

• It's the constructor of the class.

theClass = MyBasicClass()

• It's the function that you create in the

class.

theClass.myFunction()

Page 136: Introduction to Swift (tutorial)

• Create a class MyClass1, which herites of the class MyBasicClass. And create a new function myFunction2().class MyClass1: MyBasicClass {

func myFunction2() {

println ("Call of myFunction2")

}

}

Page 137: Introduction to Swift (tutorial)

• Create a new variable theClass1 of type MyClass1. Instantiate the class MyClass1 then call the functions myFunction() and myFunction2().var theClass1: MyClass1

theClass1 = MyClass1()

theClass1.myFunction()

theClass1.myFunction2()

Page 138: Introduction to Swift (tutorial)

• Create a new class MyClass2, which herites of MyBasicClass. And overload (override) the class myFunction().class MyClass2: MyBasicClass {

override func myFunction() {

println ("Call of override myFunction")

}

}

Page 139: Introduction to Swift (tutorial)

• Create a variable theClass2 of type

MyClass2. Instantiate the class MyClass2

then call the function myFunction().

var theClass2: MyClass2

theClass2 = MyClass2()

theClass2.myFunction()

Page 140: Introduction to Swift (tutorial)

• Take back the class MyBasicClass of the previous lesson.class MyBasicClass {

init() {

println ("Init")

}

func myFunction() {

println ("Call of myFunction")

}

}

Page 141: Introduction to Swift (tutorial)

• Create a class MyClass3, which herites of MyBasicClass having two properties, myInternalValue and myVar, and a getter and a setter for this property. class MyClass3: MyBasicClass {

• Create a property myInternalValue.var myInternalValue: Int

• Add a constructor with the parameter "newValue".init (newValue: Int) {

• The value provided in parameter in the constructor is attributed to the property myInternalValue. It's a way to initialize this property.

self.myInternalValue = newValue

super.init()

}

Page 142: Introduction to Swift (tutorial)

• Create a new property, myVar.var myVar: Int {

• Create a getter for the property myVar.get {

return myInternalValue

}

• Create a setter for the property myVar.set {

myInternalValue = newValue

}

}

}

Page 143: Introduction to Swift (tutorial)

• Declare a variable theClass3 of type MyClass3. var theClass3: MyClass3

• Instantiate the class and give as argument to the constructor the value used to initialize the property myInternalValue. theClass3 = MyClass3 (newValue: 3)

Page 144: Introduction to Swift (tutorial)

THE EXTENSIONS

Watch on Youtube !

Watch on Youku !

Page 145: Introduction to Swift (tutorial)

• In this lesson, you will learn to use the

extensions in Swift.

Page 146: Introduction to Swift (tutorial)

• Extend the type Array by addig a method getFirst().

• Specify that we want to extend the type Array.extension Array {

• Create a function getFirst() returning any type (Any).func getFirst() -> Any? {

• Return the first item of the array.return self [0]

}

}

Page 147: Introduction to Swift (tutorial)

• Create an array theCities and call the method getFirst().var theCities = ["Paris",

"Marseille"]

println (theCities.getFirst())

• The first item of the array is displayed in the console.

Page 148: Introduction to Swift (tutorial)

THE OVERLOAD OF

OPERATORS

Watch on Youtube !

Watch on Youku !

Page 149: Introduction to Swift (tutorial)

• In this lesson, you will learn to use the

overloads of operators in Swift.

Page 150: Introduction to Swift (tutorial)

• Create a structure Vector2D including two

floats.

struct Vector2D {

var x = 0.0

var y = 0.0

}

Page 151: Introduction to Swift (tutorial)

• Create a function for the operator + on the types Vector2D. The function adds simply each component of the vectors. @infix func + (left: Vector2D, right:

Vector2D) -> Vector2D {

return Vector2D (x: left.x +

right.x, y: left.y + right.y)

}

Page 152: Introduction to Swift (tutorial)

• To use it, create two variables Vector2D then use the operator + that you just created.var value1: Vector2D = Vector2D (x: 1.5, y: 2.5)

var value2: Vector2D = Vector2D (x: 3.5, y: 4.5)

var value3 = value1 + value2

println (value3)

value3

Page 153: Introduction to Swift (tutorial)

• Now, modify the operator + on two integers. Instead of doing an addition, do a substraction.@infix func + (a: Int, b: Int) ->

Int {

return a - b

}

Page 154: Introduction to Swift (tutorial)

• If you compute "5 + 4", it returns the result

"5 - 4", it means 1.

var a = 5 + 4

println (a)

Page 155: Introduction to Swift (tutorial)

Follow me on my channel PengYooTV …

On my Youku channelhttp://i.youku.com/brunoparis

Who am I ?

Bruno Delb (www.delb.cn),

Author of the first french book of development of Java mobile application (2002),

Consultant, project manager and developer of social & mobile applications,

let’s talk about your needs ...

And on Weibo :http://www.weibo.com/brunodelb