swift 4 - geektuga.ddns.net · core os • contains the low-level features that most other...

169
Swift 4

Upload: others

Post on 04-Jul-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift 4

Page 2: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Conteúdos

• O que é

• Swift vs Objective-C

• ARC

Page 3: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Conteúdos• Swift

• Tipos de dados

• int

• String

• Float vs Double

• Literais

Page 4: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Conteúdos• Swift

• Variáveis e constantes

• Criação e utilização

• Nomes legais

• Operações

• Tuplos

Page 5: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Conteúdos• Swift

• Opcionais

• O que são?

• Opcionais vs Variável / Constante

• Criação

• Utilização

• Funções

Page 6: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Conteúdos• Swift

• Colections

• Array

• Dicionários

• Sets

Page 7: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Conteúdos• Swift

• for

• if

• switch/case

• while

Page 8: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Conteúdos• Swift

• Classes

• Estruturas

Page 9: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

O que é?• Linguagem de desenvolvimento Apple

• Funciona com Cocoa e Cocoa Touch

• “Compatível” com Objective-C

• Inspirada em Objective-C, Ruby, Python, C#, etc

• 1 versão publica 9/9/2014

Page 10: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

O que é?

• Linguagem moderna

• Escrita eficiente

Page 11: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift vs Objective-C

• Necessidade de ;

• Objective-C -> obrigatório

• Swift -> não obrigatório

Page 12: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift vs Objective-C• Declaração de variáveis

• Objective-C

• tipo nome=valor;

• Swift

• var nome:tipo = valor

Page 13: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift vs Objective-C• Declaração de variáveis (String)

• Objective-C

• NSString *titulo = @“E tudo o vento levou”;

• Swift

• var titulo:String = “E tudo o vento levou”

Page 14: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift vs Objective-C• Declaração de métodos

• Objective-C

• modificador(retorno) nome { }

• Swift

• modificador func nome() ->retorno { }

Page 15: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift vs Objective-C

• Declaração de métodos

• Objective-C

- (NSMutableArray*)getBusStops:(NSString*)busStop forTime:(NSSTimeInterval*)timeInterval;

• Swift

• modificador func nome(a:Int) ->Int { }

Page 16: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift vs Objective-C• declaração de Classes

• Objective-C

• someObject *myobj = [[someObject alloc]init];

• Swift

• var myobj = someObject()

Page 17: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

ARC

• ARC = Automatic reference counting

• Limpeza de memoria automatica

• Não disponível em Objective-C

Page 18: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

• Tudo são Objectos

Page 19: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Playground

Page 20: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

o que é?

• Ambiente interativo de programação

• Parte integrante do Xcode

Page 21: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Utilizações

• Aprender uma nova linguagem

• Criação de protótipos

• Testar scripts

Page 22: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Alternativa online

Page 23: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your
Page 24: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Como criar um projecto Playground

Page 25: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

• Demonstração

Page 26: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

• Criação de Variáveis (Inferred data type )

• var name = value: var a = 10 var b = "ola mundo" var c = true

Page 27: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

• Criação de constantes (Inferred data type )

• let name = value: let a = 10 let b = "ola mundo" let c = true

Page 28: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift• Criação de var/let com tipo definido

explicitamente

• var name:dataType

let inteiro:Int let bool:Bool var doable:Double let float:Float var str:String

Page 29: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

• Operações com var/let

var soma = 2+2 var div = 2/2 var multip = 3*2 var resto = 10%3

Page 30: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

• Controlo de fluxo

• If

• Switch

Page 31: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

• Controlo de fluxo - > if

if condition { code }

Page 32: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

• Controlo de fluxo - > if

if true { //do something }

Page 33: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

• Controlo de fluxo - > switch

switch Value { case pattern: code default: code }

Page 34: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

• Controlo de fluxo - > switch

switch a { case 1: //do something case 2: //do something default: //do something else }

Page 35: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your
Page 36: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Demo

Page 37: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Demo

Page 38: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

• Loops

• for

• while

Page 39: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

• Loop - > for

for a in collection{

//do something

}

Page 40: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

• Loop - > while

while true{

//do something

}

Page 41: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

iOS Technologies

Page 42: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

• The iOS is the operating system that runs on iPad, iPhone, and iPod touch devices.

• The operating system:

• Manages the device hardware and provides the technologies required to implement native apps.

Page 43: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

• The iOS Software Development Kit (SDK) contains the tools and interfaces needed to develop, install, run, and test native apps that appear on an iOS device’s Home screen.

• Native apps are built using the iOS system frameworks and Objective-C/Swift languages and run directly on iOS and they are installed physically on a device

Page 44: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

The iOS SDK provides the resources you need to develop native iOS apps

Page 45: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

The iOS Architecture Is Layered

Page 46: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

• It is recommended that you prefer the use of higher-level frameworks over lower-level frameworks whenever possible.

• The higher-level frameworks are there to provide object-oriented abstractions for lower-level constructs.

• These abstractions generally make it much easier to write code because they reduce the amount of code you have to write

• You may use lower-level frameworks and technologies, too, if they contain features not exposed by the higher-level frameworks.

Page 47: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Core OS• Contains the low-level features that most other

technologies are built upon.

• Even if you do not use these technologies directly in your apps, they are most likely being used by other frameworks.

• And in situations where you need to explicitly deal with security or communicating with an external hardware accessory, you do so using the frameworks in this layer.

Page 48: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Core Services

• Contains fundamental system services for apps. Key among these services are the Core Foundation and Foundation frameworks, which define the basic types that all apps use.

• This layer also contains individual technologies to support features such as location, iCloud, social media, and networking.

Page 49: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Core Services

• Peer-to-Peer Services

• iCloud Storage

• File-Sharing Support

• In-App Purchase

Page 50: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Frameworks of the Core Services

• Address Book Framework

• Ad Support Framework

• CloudKit Framework

• Core Data Framework

• Core Location Framework

• HealthKit Framework

• HomeKit Framework

Page 51: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Media Layer

• Contains the graphics, audio, and video technologies you use to implement multimedia experiences in your apps.

• The technologies in this layer make it easy for you to build apps that look and sound great.

Page 52: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Media Layer

• Graphics Technologies

• Audio Technologies

• Video Technologies

• AirPlay

Page 53: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Frameworks of the Media Layer

• Core Audio

• Core Graphics Framework

• Game Controller Framework

• Image I/O Framework

• SpriteKit Framework

Page 54: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Cocoa Touch

• Contains key frameworks for building iOS apps.

• These frameworks define the appearance of your app and provide the basic app infrastructure and support for key technologies such as multitasking, touch-based input, push notifications, and many high-level system services.

Page 55: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Cocoa Touch• App Extensions

• AirDrop

• TextKit

• Multitasking

• Auto Layout

• Storyboards

Page 56: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Frameworks of the Cocoa Touch

• Address Book UI Framework

• GameKit Framework

• iAd Framework

• PushKit Framework

• UIKit Framework

Page 57: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Anatomy of an app

Page 58: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

• Uma app iOS é basicamente um conjunto de objectos que envia mensagens para outros objectos

• Uma boa parte dos objectos são fornecidos pela api

Page 59: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

• No iOS as apps são event-driven o que significa que os objectos estão a “escuta” de determinados eventos e quando eles ocorrem estes são processados

Page 60: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

• De forma geral na maioria do tempo uma app esta sem fazer nada, apenas actua quando acontece algum evento

Page 61: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your
Page 62: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

SWIFT 101INTRODUÇÃO AO SWIFT

Page 63: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

BASICO

▸ Linguagem Fortemente tipada

▸ Inferência de tipos

▸ Case sensitive

▸ Sem necessidade do ;

▸ “Não há” valores nil (variáveis sem valor)

�2

Page 64: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

TIPOS DE DADOS BÁSICOS

▸ String - “Ola mundo @ 2018”

▸ Int - 123456789

▸ Double 1.1234 (Precisão de 15 a 16 casas decimais)

▸ Float 1.2345 (Precisão de 7 casas decimais)

▸ Boolean - true ou false

�3

Page 65: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

VARIÁVEIS E CONSTANTES

▸ “caixa de sapatos” onde guardamos valores

▸ Identificador de uma posição em memória onde os dados são armazenados

▸ Variáveis - o seu conteúdo pode mudar

▸ Constantes - depois de inicializadas o seu valor não pode mudar

�4

Page 66: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

DECLARAÇÃO - VARIÁVEIS E CONSTANTES

▸ Inferencia de tipo var/let nome = valor

var numero = 10

let numero = true

▸ Tipo Explicito var nome:tipo = valor

var numero:Int = 10

let numero:Int = 10

�5

Page 67: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

CASTING - VARIÁVEIS E CONSTANTES

▸ Conversão de tipos NovoTipo(nomeVar)

var x = 10

var z = String(x)

�6

Page 68: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

OPERAÇÕES COM VARIÁVEIS E CONSTANTES

▸ Apenas são possíveis operações com variáveis do mesmo tipo

▸ Operações em Swift

▸ +

▸ -

▸ /

▸ *

▸ %

�7

Page 69: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

OPERAÇÕES COM VARIÁVEIS E CONSTANTES

▸ Incremento

▸ ++ /- - não disponível

▸ += 1

▸ -= 1

▸ *= 1

�8

Page 70: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

TUPLOS

▸ Variáveis que podem conter mais que um elemento

▸ Inferencia de tipo var v1 = (1, “Dois”, true)

let v1 = (id:1, nome:“Dois”, inscrito:true)

▸ tipo Explicito let v1:(Int, String, Bool) = (1, “Dois”, true)

var v1 (id:Int, nome:String, inscrito:Bool) = (id:1, nome:“Dois”, inscrito:true)

�9

Page 71: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

ESTRUTURAS DE CONTROLE

▸ if

▸ switch / case

�10

Page 72: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

ESTRUTURAS DE CONTROLE - IF

▸ if if condition { code }

▸ switch / case switch Value { case pattern: code default: code }

�11

Page 73: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

ESTRUTURAS DE REPETIÇÃO

▸ for

▸ while

▸ do/while

�12

Page 74: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

ESTRUTURAS DE REPETIÇÃO

▸ for for a in collection{

//do something

}

▸ while while true{

//do something

}

�13

Page 75: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

OPCIONAIS

▸ Variáveis que podem ou não ter valor

▸ Forma de atribuir valor nil

▸ Para serem utilizados tem de ser unwrapped

�14

Page 76: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

OPCIONAIS

▸ Criar opcionais var a:Int? // nil

var a:Int? = 10 // Optional(10)

var a:Int? a = 10 // Optional(10)

�15

Page 77: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

OPCIONAIS

‣ Operações com opcionais

var a:Int? a = 10 // Optional(10) a = nil // nil

var a:Int a = 10 // 10 a = nil // Erro

�16

Page 78: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

OPCIONAIS

▸ unwrap opcionais var a:Int? = 10 // Optional(10)

a! // 10

a // Optional(10)

�17

Page 79: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

OPCIONAIS

▸ ! vs ?

�18

Page 80: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

OPCIONAIS

▸ unwrap opcionais var a:Int? = 10 // Optional(10)

if let x = a {

print(x) // 10

}

�19

Page 81: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

OPCIONAIS

▸ unwrap opcionais var a:Int? = 10 // Optional(10)

var x = a ?? 0 //10

var a:Int? // nil

var x = a ?? 0 // 0

guard let t = a else { return }

�20

Page 82: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

COLLECTIONS

▸ Array

▸ Set

▸ Dicionários

�21

Page 83: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

COLLECTIONS - ARRAYS

▸ Conjunto ordenado

▸ Os valores são acedidos através do seu index

▸ Criação de arrays let arr:[Int]

▸ Criação de arrays let arr = [] let arr = [1,2,3,4,5,6]

�22

Page 84: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

COLLECTIONS - ARRAYS

▸ Adicionar elementos arr.append(10)

▸ Remover elementos var x = arr.popLast()

var x = arr.remove(at: 0)

▸ Aceder a um elemento x[0]

�23

Page 85: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

▸ Listar os valores do array for a in arr{

print(a)

}

arr.forEach{ a in

print(a)

}

COLLECTIONS - ARRAYS

�24

Page 86: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

COLLECTIONS - DICIONÁRIOS

▸ Conjunto Chave - Valor

▸ Não ordenado

▸ Os valores são acedidos através da seu chave

▸ Criação de Dicionários let dict:[String:String]

▸ Instanciação de Dicionários let dict = [:] let dict = [“nome”:”Gonçalo”, “lastName”:”Feliciano”]

�25

Page 87: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

COLLECTIONS - DICIONÁRIOS

▸ Ler elementos dict[key]

▸ Adicionar elementos dict[New key] = new value

▸ Remover elementos dict[key] = nil

�26

Page 88: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

▸ Listar os valores do array for a in dic{

print(a)

}

dic.forEach{ a in

print(a)

}

COLLECTIONS - ARRAYS

�27

Page 89: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

COLLECTIONS - SETS

▸ Conjuntos de Valores

▸ Não ordenado

▸ Não contem valores repetidos

▸ Criação de Sets let set:Set<String>

▸ Instanciação de Sets let set = Set<String>() let arr:Set = [”ovos”, “açúcar”, “farinha”]

�28

Page 90: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

▸ Iterar pelo set for a in set{

print(a)

}

COLLECTIONS - SETS

�29

Page 91: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

▸ Adicionar elementos set.insert(“mel")

▸ Remover elementos var x = set.remove(“ovos”)

COLLECTIONS - SETS

�30

Page 92: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

COLLECTIONS - SETS

�31

Page 93: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

INTRODUÇÃO AO SWIFT

O QUE DEVO SABER NESTE PONTO

▸ Os tipos de dados básicos disponíveis em Swift

▸ Criar e manipular variáveis e constantes

▸ Tuplos

▸ Estruturas de control

▸ Loops

▸ Opcionais

▸ Collections

�32

Page 94: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Swift

Page 95: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Class e Structs

Page 96: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Conteúdos

• O que são classes

• Class vs estruturas

• Como criar classes e estruturas

• Metodos

• Herança

Page 97: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Conteúdos

• Propriedades

• Lazy property

• Propriedades computadas

• Property observer

Page 98: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Class

• São o molde para criar objectos

• Tem métodos (funções) e propriedades

• Devem ser declaradas no seu próprio ficheiro

• O seu nome deve começar por maiúscula e ser CamelCase (AlunoUniv)

Page 99: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Class vs estruturas • As estruturas e class têm muito em comum:

• Definem propriedades

• Definem metodos

• Definem sub-scripts

• Podem conter um constructor personalizado

• Entre outras

Page 100: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Class vs estruturas

• as classes podem:

• Herdar de outras classes

• Podem ter mais de uma referência

Page 101: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

class / structs

• classes são Reference Type

• structs:

• são value type

• tem um init predefinido

Page 102: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Criar class

class nome{

//codigo da class

}

Page 103: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Criar struct

struct nome{

//codigo da struct

}

Page 104: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Instanciar uma struct

struct resulocao{ var w:Int var h:Int

}

let porjector = resulocao(w:800, h:900)

Page 105: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Instanciar uma class

class aluno{

var nome:String? var idade:Int?

}

let joao = aluno()

joao.nome = “João”

Page 106: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Inicializar uma class

class Carro{ var marca:String private var ano:Int

init(nome:String, ano:Int) { self.marca = nome self.ano = ano }

}

let bmw = Carro(nome:“bmw”, ano:2000)

Page 107: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Operador de identidade

• === -> identica

• !== -> não identica

Page 108: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

DEMO

Page 109: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Quando usar Structs

• Agrupar valores simples

• Quando os valores são value type

• Quando não é necessário herdar comportamentos ou propriedades

Page 110: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Quando usar Structs

• Definir formas geométricas

• Coordenadas

• etc

Page 111: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Herança

Page 112: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Herança• Uma class pode herdar métodos e propriedades de outra

• A class que herda é denominada de sub class

• A class da qual se herda é denominada de super class

• É possível aceder a métodos e propriedades

• O overriding é possível

• O swift tem forma de garantir que este processo e feito correctamente

Page 113: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Herança

• Podem ser adicionados observers as propriedades herdadas

Page 114: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Sintax

class SubClass: SuperClass{

//code here

}

Page 115: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Exemplo

class Pessoa{ var nome:String var idade:Int init(nome:String,idade:Int ){ self.nome = nome self.idade = idade } func infos(){ print("\(self.idade), \(self.nome)") } }

Page 116: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Exemplo

class Medico: Pessoa{ var exp:String

init(nome: String, idade: Int, exp:String) { self.exp = exp super.init(nome: nome, idade: idade) } func dados() { super.infos() print("-------------") print(“nome: \(super.nome),\nage: \(super.idade),\nexp: \(self.exp)") } }

Page 117: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Exemplo

var rita = Medico(nome: "rita", idade: 30, exp: "clinica geral") rita.dados()

rita.infos();

Page 118: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

DEMO

Page 119: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Overriding

Page 120: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Overriding

• Forma de uma sub class alterar a funcionalidade de instance methods, class methods, instance propertys, class propertys e sub-scripts

• Em Swift é necessário indicar de forma explicita que um método re-escreve um método da super class

Page 121: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Overriding

class Dog { func bark () { print("woof")

} }

class NoisyDog : Dog { override func bark () { print("woof woof woof") } }

Page 122: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Overriding

• Apesar de re-escrito ainda podemos aceder ao método original

Page 123: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Overridingclass Dog { func bark () { print("woof") } }

class NoisyDog : Dog { override func bark () { for _ in 1...3 { super.bark() }

} }

class VeryNoisyDog : Dog { override func bark () { for _ in 1…5 { super.bark() }

} }

Page 124: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Overriding

• Para evitar que algo seja re-escrito deve ser declarado como final

Page 125: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Overriding

class Dog {

final func bark () { print("woof") } }

Page 126: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Overriding

• Com o Overriding a propriedades podemos adicionar gettres e settres observers próprios

• A class que herda não sabe nada das propriedades herdades para alem do seu nome e tipo

Page 127: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Overriding

class SuperCar:Car{ var gear = 1 override var desc: String{ return super.desc + “ in gear \(gear)”

} }

Page 128: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Propriedades

Page 129: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Propriedades

• Uma propriedade e uma variável declarada no top level de um objecto

• Há dois tipos de propriedades

• Instance properties

• Static/class properties.

Page 130: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Instance properties• Instance properties

• Se nada foi dito em contrario uma propriedade e sempre instance property.

• O seu valor pode variar a cada instancia da class

• A variável “vive” enquanto a instância a qual esta associada “viver”

Page 131: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Static/class properties.

• A property is a static/class property if its declaration is preceded by the keyword static or class.

• Its lifetime is the same as the lifetime of the object type.

Page 132: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Local variables

• A local variable is a variable declared inside a function body.

• A local variable lives only as long as its surrounding curly-braces scope lives

Page 133: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Computed Initializer

Page 134: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Computed Initializer

• Por vezes necessitados de ter varias linhas de código para inicializar uma variável, em Swift isto pode ser feito de forma compacta

Page 135: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Computed Initializer

let timed : Bool = { if val == 1 { return true } else { return false } }()

Page 136: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Computed Variables

Page 137: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Computed Variables

• Até agora inicializamos variáveis atribuindo-lhe um valor.

• Em Swift as variáveis pode ser computadas, ou seja em vez de terem valores têm funções

• setter - chamada quando lhe e atribuído valor

• getter - chamada quando acedemos ao “valor” ou seja quando esta e referida

Page 138: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Computed Variables

• As variáveis computadas podem ser usadas nas mais vaiadas situações

• Variáveis so de leitura

• Façade for a function

• Façade for other variables

Page 139: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Computed Variables

class Quadrado { var lado:Float? var area:Float { set{ self.lado = sqrt(newValue) } get{ return pow(self.lado!, 2) } } var perimetro:Float { set{ self.lado = newValue/4 } get{ return self.lado! * 4 } } }

Page 140: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Variáveis so de leitura

• As variáveis computadas pode ser apenas de leitura ou seja não sendo possível serem alteradas

Page 141: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Variáveis so de leitura

var estado : String { get { if media >= 9.5 { return "Aprovado com media de \(self.media)" }else{ return "não aprovado com media de \(self.media)" } } }

Page 142: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Façade for a function

• Variáveis computadas podem retornar apenas o resultado de uma função

Page 143: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Façade for a function

var mp : MPMusicPlayerController { return MPMusicPlayerController.systemMusicPlayer() }

Page 144: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Façade for other variables

• Uma variável computada pode fazer de “interface” entre o utilizador e o programa, funcionando como um “gatekeeper”

• Semelhante ao getter e setter em C#

Page 145: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Façade for other variables

private var _p : String

var p : String { get { return self._p

} set {

self._p = newValue }

}

Page 146: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Setter Observers

Page 147: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Setter Observers

• Outra forma de injectar funcionalidade em settres

• Os Observers são funções chamadas antes e depois de uma variável ser alterada

• Não são chamados quando a variável e inicializada

Page 148: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Setter Observers

var s = "whatever" { willSet { print(newValue) }

didSet { print(oldValue)

} }

Page 149: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

DEMO

Page 150: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Lazy property

Page 151: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Lazy property

• Se uma variável e inicializada com um determinado valor e for usada a lazy initialization este valor só é avaliado quando o programa tenta aceder a essa variável

Page 152: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Lazy property

• Em Swift há 3 tipos de propriedades que podem ser “lazy”

• Variáveis Globais

• Static properties

• Instance properties

Page 153: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Lazy property

• As Lazy instance properties:

• Não podem ser let

• Não podem ter observers

• Não podem ser so de leitura

Page 154: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Lazy property

• Para que serve?

• Em que situações faz sentido que sejam usadas ?

Page 155: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Lazy property

• Quando o valor inicial e “caro” de gerar / ler

• Quando o seu valor depende de factores externos

Page 156: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Lazy property

• Podem fazer coisas que as propriedades normais não podem:

• Podem-se referir a propria instancia

Page 157: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Lazy property

class MyView : UIView {

lazy var arrow : UIImage = self.arrowImage()

func arrowImage () -> UIImage { // ... big image-generating code goes here ... }

}

Page 158: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Protocolos

Page 159: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Protocolos

• Implementam um “blueprint” de métodos e propriedades

• Forma de partilhar propriedades e funcionalidades por objectos não relacionados

• Atribui um novo tipo ao objecto

• Semelhante as interfaces do Java / C#

Page 160: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Protocolos

protocol someProtocol {

//code goes here

}

Page 161: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Protocolos

• Podem ser implementados tanto em class como em struts

Page 162: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Protocolos

struct structName: protocolA, protocolB {

//code goes here

}

Page 163: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Protocolos

class className: superClass, protocolA, protocolB {

//code goes here

}

Page 164: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Protocolos• Tudo o que estiver declarado no protocolo deve ser

implementado

• Pode implementar protocolos

• Se o protocolo implementa uma propriedade

• Com getter e settres nunca poderá ser declarada como constante ou de leitura

• Se apenas tiver implementado o getter, pode ser declarada como qualquer propriedades

Page 165: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Protocolos

protocol SomeProtocol {

var someInt:Int {get set} var someOtherInt:Int {get}

}

Page 166: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Protocolos

protocol SomeProtocol2 {

func random() -> Double

}

Page 167: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Protocolos

class className: SomeProtocol, SomeProtocol2 {

var someInt: Int = 0; var someOtherInt: Int = 0;

func random() -> Double{

//code goes here

}

}

Page 168: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Qual a importancia dos Protocolos?

Page 169: Swift 4 - geektuga.ddns.net · Core OS • Contains the low-level features that most other technologies are built upon. • Even if you do not use these technologies directly in your

Protocolos

• Usado em alguns design patterns

• Polimorfismo