Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introdução ao Swift - CocoaHeads BH

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on. →

Introdução ao Swift - CocoaHeads BH

Salmo Junior

April 26, 2016

Transcript

68 slides
  1. Salmo Junior Mineiro, Chapter Leader do CocoaHeads BH, dev iOS

    desde 2011, corinthiano, viajante e viciado em queijo. [email protected] @salmojr
  2. 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
  3. Swift 4 Mais veloz 4 Mais segura 4 Linguagem "nova"

    4 Versão atual 2.2 4 3.0 a caminho
  4. Swift Uma simples linha pode ser considerada um programa em

    swift. print("Olá CocoaHeads Beagá")
  5. 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
  6. Declaração let name = "John" var age = 25 age

    = 26 print("Sua idade é \(age)")
  7. 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)
  8. Tipos Swift é fortemente tipada. Para casos em que o

    tipo não é passado, ela tentará inferir o tipo ao receber o valor.
  9. 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"
  10. 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
  11. 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")
  12. 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++
  13. 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
  14. Struct e Class 4 Struct - Value Types 4 Class

    - Reference Types struct SomeStructure { // structure definition goes here } class SomeClass { // class definition goes here }
  15. 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)
  16. 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)
  17. Class Mas Classes tem funcionalidades a mais que Structs 4

    Herança 4 Type Casting 4 Desinicializadores 4 Reference count
  18. 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) } }
  19. 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."); } }
  20. 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
  21. 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()
  22. 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)")
  23. Enums Case com paramêtros enum Types { case Str(String) case

    Num(Double) } var type = Types.Str("hello") type = .Num(1.0)
  24. 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 } }
  25. Níveis de acesso Existem 3 tipos de níveis de acesso

    4 Public 4 Internal 4 Private 4 Protected
  26. Níveis de acesso public class SomeClass { private var someProperty:

    Int = 0 internal func someFunc() -> Int { return someProperty } }
  27. Optionals Definimos que uma var pode ser nil atribuindo o

    símbolo ?. var possibleString: String? var possibleNum: Int?
  28. Optionals Validando se existe valor utilizando if-let var possibleNum: Int?

    possibleNum = Int("ABC") if let num = possibleNum { //Seguro utilizar "num", existe um valor }
  29. Optionals Validando se existe valor utilizando guard-let func someFunc(possibleNum: Int?)

    { guard let num = possibleNum else { return } print("Número = \(num)") }
  30. 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"))
  31. 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()
  32. 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. } } }
  33. 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)
  34. 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
  35. 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)
  36. 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)")
  37. 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 }
  38. Closures // Uma closure sem parâmetros que retorna uma String

    var hello: () -> (String) = { return "Hello!" } hello() // Hello!
  39. 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
  40. Extensions Adiciona novos comportamentos em Classes, Structs, Enums e Protocols

    já existentes. extension Int { var simpleDescription: String { return "The number \(self)" } } print(7.simpleDescription)
  41. Extensions extension Double { var abs: Double { get {

    return fabs(self) } } } var testDouble = -10 testDouble.abs // 10
  42. 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() }
  43. Protocols struct TestStruct: SomeProtocol { func doSomethingNonOptionalMethod(){ } } class

    TestClass: SomeProtocol { func doSomethingNonOptionalMethod() { } } enum TestEnum: SomeProtocol { func doSomethingNonOptionalMethod() { } }
  44. Protocols Deixando o código mais organizado e legível extension TestClass:

    SomeProtocol { func doSomethingNonOptionalMethod() { } }
  45. 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

More Decks by Salmo Junior

Other Decks in Technology