Introduction to Swift programming language.

22
Introduction to Swift @RoelCastano June 23, 2014

Transcript of Introduction to Swift programming language.

Page 1: Introduction to Swift programming language.

Introduction to Swift@RoelCastano June 23, 2014

Page 2: Introduction to Swift programming language.

Swift vs Objective-C

#include <stdio.h>

int main(){ printf(“hello, world\n”); return 0; }

println(“hello, world”)

Page 3: Introduction to Swift programming language.

Variables

let dogName: String = “Cinnamon” !var age: Double = 8.5 !var inferredType = “String” !let 🐝 = “Bee”

for character in “string” { println(character) } // s // t // r // i // n // g !———————————————- !let a = 3, b = 5 let stringResult = “\(a) times \(b) is \(a * b)”

Page 4: Introduction to Swift programming language.

more strings

var variableSting = “Apple” variableString += “ and Pixar” // variableString is now “Apple and Pixar” !let constantString = “Apple” constantString += “ and Microsoft” // constant can’t be changed !//castinglet label = "The width is "let width = 94_000_00let widthLabel: String = label + String(width) !

Page 5: Introduction to Swift programming language.

Optionals and TypeAlias

//Optionals !var dogAge = "123".toInt() if dogAge { //is either nil or Int     dogAge! //now it is an Int } !var someValue: String? someValue = "Fido" !someValue = nil

//typealias !typealias 👬 = Double var size: 👬 = 12.2 !typealias Point = (Int, Int) let origin: Point = (0, 0)

Page 6: Introduction to Swift programming language.

Tuples

//unnamed tuples var luckyNumbers: = (3, 8, 21) luckyNumbers.2 //21 !//named tuples var myDog:(Int, Int, Bool) = (age: 8, isAFemale: true) var (age,_) = myDog age //6 !!

Page 7: Introduction to Swift programming language.

Arrays

/* Notes: These arrays can only be of one types, not like NSArray or NSDictionary, which can have any object. */ !//array (String[] optional) let emptyArray = String[]() !var shoppingList: String[] = ["catfish", "water", "tulips", "blue paint"] //prefered var numberList: Array<Int> = [1,2,3,4,5] var numberList2 = [11,22,33,44,55] //preferred !shoppingList.append("milk") !for (index, object) in enumerate(shoppingList){ println("The object #\(index) is a \(object)") } !var possibleNames = Array(count: 10, repeatedValue: "BRO")

Page 8: Introduction to Swift programming language.

Dictionaries

//dictionary let emptyDictionary = Dictionary<String, Float>() !var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations" occupations.updateValue("Chief", forKey:"Malcolm") occupations.removeValueForKey("Kaylee") occupations !var employees = Array(occupations.keys) !for (name, occupation) in occupations { println("Name: \(name) \n Occupation: \(occupation)") } !

Page 9: Introduction to Swift programming language.

If-Else and Switch

// If-Else !var optionalString: String? = "Hello" optionalString == nil !var optionalName: String? = nil var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" } else { let name = String("Some Name") }

// Switch !let vegetable = "red pepper" switch vegetable { ! case “celery": let vegetableComment = "Add some raisins and make ants on a log.” ! case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich.” ! case let x where x.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(x)?” ! default: let vegetableComment = "Everything tastes good in soup.” }

Page 10: Introduction to Swift programming language.

For Loop

let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25], ] var largest = 0 var largestKind:String? = nil for (kind, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number largestKind = kind } } } largest //25 largestKind //square

var firstForLoop = 0 for i in 0..3 { firstForLoop += i } firstForLoop // 3 !———————————————————————————————— !var firstForLoop = 0 for i in 0...3 { secondForLoop += i } secondForLoop // 6

Page 11: Introduction to Swift programming language.

Functions

func count(string: String) -> (vowels: Int, consonants: Int, others: Int) { var vowels = 0, consonants = 0, others = 0 for character in string { switch String(character).lowercaseString { case "a", "e", "i", "o", "u": ++vowels case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z": ++consonants default: ++others } } return (vowels, consonants, others) } !let total = count("some arbitrary string!") let finalString = "\(total.vowels) vowels and \(total.consonants) consonants" // prints "6 vowels and 13 consonants"

Page 12: Introduction to Swift programming language.

Functions and Generics

func swapTwoInts(inout a: Int, inout b: Int) { let temporaryA = a a = b b = temporaryA } !var someInt = 3 var anotherInt = 107 swapTwoInts(&someInt, &anotherInt) let newInts = "someInt is now \(someInt), and anotherInt is now \(anotherInt)" // prints "someInt is now 107, and anotherInt is now 3"

Page 13: Introduction to Swift programming language.

Generics

!func swapTwoValues<T>(inout a: T, inout b: T) { let temporaryA = a a = b b = temporaryA } !var designer = "Lentes" var programmer = "Alice" swapTwoValues(&designer, &programmer) let newTeam = "designer is now \(designer), and programmer is now \(programmer)" // prints "designer is now Alice, and programmer is now Lentes"

Page 14: Introduction to Swift programming language.

Structures vs Classes

Consider Structure when:

Encapsulate simple data values

Values would be copied rather than referenced.

Any properties stored by the structure are themselves value types.

Ex. Geometric Shapes, Coordinates, Person.

Consider Classes when:

Inheritance should be used.

Need more than one reference to the same instance

Check or Interpret the type of a class at runtime

Ex. Real life complex objects.

Page 15: Introduction to Swift programming language.

Classes

class Vehicle { var numberOfWheels: Int var maxPassengers: Int func description() -> String { return "\(numberOfWheels) wheels; up to \(maxPassengers) passengers" } init() { numberOfWheels = 0 maxPassengers = 1 } }

class Bicycle: Vehicle { init() { super.init() numberOfWheels = 2 } }

class Tandem: Bicycle { init() { super.init() maxPassengers = 2 } } let tandem = Tandem() println("Tandem: \(tandem.description())”) // Tandem: 2 wheels; up to 2 passengers

Page 16: Introduction to Swift programming language.

Method Overriding

class Car: Vehicle { var speed: Double = 0.0 init() { super.init() maxPassengers = 5 numberOfWheels = 4 } override func description() -> String { return super.description() + "; " + "traveling at \(speed) mph" } } let car = Car() println("Car: \(car.description())") // Car: 4 wheels; up to 5 passengers; traveling at 0.0 mph

Page 17: Introduction to Swift programming language.

Property Overriding

class SpeedLimitedCar: Car { override var speed: Double { get { return super.speed } set { super.speed = min(newValue, 40.0) } } } !let limitedCar = SpeedLimitedCar() limitedCar.speed = 60.0 println("SpeedLimitedCar: \(limitedCar.description())") // SpeedLimitedCar: 4 wheels; up to 5 passengers; traveling at 40.0 mph

Page 18: Introduction to Swift programming language.

Structs

struct Color { let red = 0.0, green = 0.0, blue = 0.0 init(red: Double, green: Double, blue: Double) { self.red = red self.green = green self.blue = blue } } !!let magenta = Color(red: 1.0, green: 0.0, blue: 1.0) !

Page 19: Introduction to Swift programming language.

Protocols

protocol FullyNamed { var fullName: String { get } } !struct Person: FullyNamed { var fullName: String } !let john = Person(fullName: "John Appleseed") // john.fullName is "John Appleseed" !

Page 20: Introduction to Swift programming language.

more protocols

!!protocol RandomNumberGenerator { func random() -> Double } !class Dice { let sides: Int let generator: RandomNumberGenerator init(sides: Int, generator: RandomNumberGenerator) { self.sides = sides self.generator = generator } func roll() -> Int { return Int(generator.random() * Double(sides)) + 1 } } !protocol TextRepresentable { func asText() -> String } !extension Dice: TextRepresentable { func asText() -> String { return "A \(sides)-sided dice" } }

Page 21: Introduction to Swift programming language.

Facts

First app built on Swift was the WWDC App.

You can use Swift, C, and Objective-C in parallel.

The book “The Swift Programming Language” was downloaded 370,000 times on one day.

Page 22: Introduction to Swift programming language.

References

Swift Tutorial Part 3: Tuples, Protocols, Delegates, and Table Views. http://www.raywenderlich.com/75289/swift-tutorial-part-3-tuples-protocols-delegates-table-views

An Introduction To Object-Oriented Programming in Swift. http://blog.codeclimate.com/blog/2014/06/19/oo-swift/

A Few Interesting Things In Swift http://www.slideshare.net/SmartLogic/a-few-interesting-things-in-swift