Share
Embed
Introdução ao Swift - CocoaHeads BH
Talk para o 7º CocoaTalks BH - http://www.meetup.com/CocoaHeads-Talks-BH/events/230397605/
Salmo Junior
April 26, 2016
Transcript
68 slides
-
Salmo Junior Mineiro, Chapter Leader do CocoaHeads BH, dev iOS
desde 2011, corinthiano, viajante e viciado em queijo. [email protected] @salmojr -
Agenda 4 Declaração e Tipos 4 Controles de fluxo 4
Struct, Class e Enums 4 Níveis de acesso 4 Optionals 4 Functions, Tuples e Closures 4 Extensions, Protocols e Generics -
Swift 4 Mais veloz 4 Mais segura 4 Linguagem "nova"
4 Versão atual 2.2 4 3.0 a caminho -
Swift Uma simples linha pode ser considerada um programa em
swift. print("Olá CocoaHeads Beagá") -
Declaração As palavras-chave let e var são utilizadas para indicar
elementos que armazenam valores. 4 var para variáveis 4 let para constantes -
Declaração let name = "John" var age = 25 age
= 26 print("Sua idade é \(age)") -
Declaração let name = "John" let age = 25 let
heigth = 1.79 let greeting = "Olá \(name), você tem \(age) anos e sua altura é" + String(format:" %.2f", heigth) -
Tipos Swift é fortemente tipada. Para casos em que o
tipo não é passado, ela tentará inferir o tipo ao receber o valor. -
Tipos //Inferido let name = "John" // String let age
= 25 //Int let heigth = 1.79 //Double //Explicito var explicitInt: Int = Int() let explicitFlout: Float = 4 let adress: String = "Avenida dos Andradas, 3000 - Sta. Efigênia" -
Tipos //Declarando Arrays var explicitArray: Array<String> = Array() var intsArray
= [Int]() var peopleArray = ["John", "Anna"] //Acessando e atribuindo valores intsArray[0] explicitArray.append("John") explicitArray.last -
Tipos //Declarando Dictionaries var dictionary: Dictionary<String, Double> = Dictionary() var
personDictionary = [String:String]() //Acessando Dictionaries personDictionary = ["name": "John", "age":"29"] personDictionary["name"] = "Joseph" personDictionary.removeValueForKey("age") -
Controles de fluxo For-in for i in 1..>10{ print(i) }
for (key, value) in dictionary { print(" key: \(key) - Value: \(value)") } for var x = 1; x <= 10; x++ -
Controles de fluxo Do-while var z = 10 repeat{ print("Executei
uma vez e sai.") } while z < 10 -
Struct e Class Em Swift, Class e Strutc tem muito
itens em comum 4 Podem ter propriedades 4 Definir métodos 4 Definir inicializadores 4 Serem extendidas e adotarem protocolos. 4 Ter Subscripts -
Struct e Class 4 Struct - Value Types 4 Class
- Reference Types struct SomeStructure { // structure definition goes here } class SomeClass { // class definition goes here } -
Struct struct Point { var x = 0, y =
0 } var a = Point() var b = a b.x = -10 func f(p: Point) { var p = p p.x = -1 } f(a) //a = (x = 0, y = 0) //b = (x = -10, y = 0) -
Class class Point { var x = 0, y =
0 } var a = Point() var b = a b.x = -10 func f(p: Point) { let p = p p.x = -1 } f(a) //a = (x = -1, y = 0) //b = (x = -1, y = 0) -
Class Mas Classes tem funcionalidades a mais que Structs 4
Herança 4 Type Casting 4 Desinicializadores 4 Reference count -
Class Herança class Train: Vehicle { override func makeNoise() {
print("Choo Choo") } } -
Class Inicialização (Designated e Convenience) class RecipeIngredient { private var
quantity: Int init(name: String, quantity: Int) { self.quantity = quantity } convenience init(name: String) { self.init(name: name, quantity: 1) } } -
Class Desinicialização class Person{ let name:String; init(name:String){ self.name = name;
println("\(name) is being initialized."); } deinit{ println("\(name) is being deInitialized."); } } -
Enums Enums em Swift são um pouco mais robustos do
que estamos acostumados. Eles podem por exemplo: 4 Ser de vários tipos 4 Receber paramêtros 4 Conformar com protocolos 4 Ter propriedades e funções -
Enums enum Suit { case Spades, Hearts, Diamonds, Clubs func
simpleDescription() -> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } } let hearts = Suit.Hearts let heartsDescription = hearts.simpleDescription() -
Enums Enum de caracteres enum CompassPoint: Character { case North
= "N" case South = "S" case East = "E" case West = "W" } let compassPoint = CompassPoint.West print("Value = \(compassPoint.rawValue)") -
Enums Case com paramêtros enum Types { case Str(String) case
Num(Double) } var type = Types.Str("hello") type = .Num(1.0) -
Enums enum TrainStatus { case OnTime case Delayed(minutes: Int) func
description() -> String { var message: String switch self { case .OnTime: message = "Train is on time." case .Delayed(let minutes): message = "Train is delayed by \(minutes) minute(s)" } return message } } -
Níveis de acesso Existem 3 tipos de níveis de acesso
4 Public 4 Internal 4 Private 4 Protected -
Níveis de acesso public class SomeClass { private var someProperty:
Int = 0 internal func someFunc() -> Int { return someProperty } } -
Optionals Forma "elegante" de trablhar com valores nulos (nil). enum
Optional<T> { case None case Some(T) } -
Optionals Definimos que uma var pode ser nil atribuindo o
símbolo ?. var possibleString: String? var possibleNum: Int? -
Optionals Validando se existe valor utilizando if-let var possibleNum: Int?
possibleNum = Int("ABC") if let num = possibleNum { //Seguro utilizar "num", existe um valor } -
Optionals Validando se existe valor utilizando guard-let func someFunc(possibleNum: Int?)
{ guard let num = possibleNum else { return } print("Número = \(num)") } -
Optionals Evite fazer forced unwrapping var possibleNum: Int? possibleNum =
Int("ABC") print(possibleNum!) // Crash -
Functions Blocos independentes de código que executam uma tarefa específica.
func sayHello(personName: String) -> String { let greeting = "Hello, " + personName + "!" return greeting } print(sayHello("Anna")) -
Functions Os métodos tem a mesma sintaxe das funções, com
a diferença que precisam estar ligados a algum tipo. class SomeClass { static func someTypeMethod() { //method implementation goes here } } SomeClass.someTypeMethod() -
Functions Definindo ações de clenup func processFile(filename: String) throws {
if exists(filename) { let file = open(filename) defer { close(file) } while let line = try file.readline() { // Work with the file. } } } -
Tuplas Valores compostos, que possibilitam uma variável ter N valores,
podendo ser de tipos diferentes. var user: (name: String, email:String, age:Int) var point = (1, 1) -
Tuples //Indicado - Nomeando paramêtros var person = (firstName: "John",
lastName: "Smith") var firstName = person.firstName // John var lastName = person.lastName // Smith //Não indicado - Acessando por index var person = ("John", "Smith") var firstName = person.0 // John var lastName = person.1 // Smith -
Tuples //Método que retorna uma tuple func calculateStatistics(scores: [Int]) ->
(min: Int, max: Int, sum: Int) { var minValue = scores[0] var maxValue = scores[0] var sum = 0 //... return (minValue, maxValue, sum) } let statistics = calculateStatistics([5, 3, 100, 3, 9]) print(statistics.sum) -
Tuples var tupla = (8, 7, 3) // Decompondo uma
tupla var (x, y, z) = tupla print("x = \(x) - y = \(y) - z = \(z)") // Decompondo uma tupla ignorando alguns argumentos var (_,_,z) = tupla print("z = \(z)") -
Closures Blocos independentes de código que podem atuar como variáveis
ou funções. São equivalentes aos blocks em Objective-C e callbacks em outras linguagens. //Sintaxe de uma closure { (parameters) -> return type in statements } -
Closures // Uma closure sem parâmetros que retorna uma String
var hello: () -> (String) = { return "Hello!" } hello() // Hello! -
Closures // Uma closure que recebe um Int e retorna
um Int var double: (Int) -> (Int) = { x in return 2 * x } double(2) // 4 // Passando uma closure para uma variável var alsoDouble = double alsoDouble(3) // 6 -
Extensions Adiciona novos comportamentos em Classes, Structs, Enums e Protocols
já existentes. extension Int { var simpleDescription: String { return "The number \(self)" } } print(7.simpleDescription) -
Extensions extension Double { var abs: Double { get {
return fabs(self) } } } var testDouble = -10 testDouble.abs // 10 -
Protocols Grupo de propriedades e métodos, sem implementação, que podem
ser adotados por Classes, Structs e Enums. protocol SomeProtocol { var simpleDescription: String { get } func doSomethingNonOptionalMethod() } -
Protocols struct TestStruct: SomeProtocol { func doSomethingNonOptionalMethod(){ } } class
TestClass: SomeProtocol { func doSomethingNonOptionalMethod() { } } enum TestEnum: SomeProtocol { func doSomethingNonOptionalMethod() { } } -
Protocols Limitando Protocols somente para Classes protocol SomeProtocol: class {
func doSomethingNonOptionalMethod() } -
Protocols Deixando o código mais organizado e legível extension TestClass:
SomeProtocol { func doSomethingNonOptionalMethod() { } } -
Dicas 4 Comece brincando com o Playground 4 Leia The
Swift Programming Language 4 Fique de olho nas mudanças que estão vindo: github.com/apple/swift-evolution