Swift for JS Developers

Created by Kevin Kazmierczak / @kazmiekr

About Me

I'm a Solutions Architect for Universal Mind. I lead teams doing HTML/JS and iOS development.

Built web apps for 15 years, started out with ColdFusion, moved to Flex, and now doing Backbone and Objective-C.

Have 3 personal apps in the app store.

I like accordions and hockey.

Overview

  • Introduction
  • Evolution
  • Swift Basics
  • Sample Playgrounds
  • How an app is built
  • Discussion

iOS Development

  • Requires a mac
  • Xcode dev environment (free)
  • Free to run code in the simulator
  • iOS Dev Program ($99)
    • Run on your devices
    • Publish to the app store

Types of Apps

Evolution of Development

Objective-C

Flavor of C that's been around for a long time.

C is scary


UIButton *b = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[b setTitle:@"Button" forState:UIControlStateNormal];
[self.view addSubview:b];
[b release];
                        

Memory Management?!

Objective-C with Manual Memory Management

Automatic Reference Counting

Meet Swift!

Fresh new language based on a handful of different 'modern' ones

Much more concise

Brackets are gone

Looks friendly to a JS developer

Warning

New comes with a price

  • Bugs
  • Spec changes
  • Everyone has to start over

What we've learned

First Apple introduces something

Apple says you should start using it

Apple says you better use it soon

Apple makes you use it

Let's get started

Swift Syntax

Prepare yourself for the lack of semicolons

I will likely add some by mistake

Variables

Strongly typed, but most types are inferred

Standard Variables

Use var to create mutable variables


var name = "Kevin"
                        

'name' is automatically typed as String

Constants

Use let to create immutable variables


let number = 57
                        

'number' is automatically typed as Int and cannot be changed

String Interpolation

How you create new strings from other values


let name = "Kevin"
let fullName = "\(name) Kazmierczak"
                        

Collection Types

Arrays and Dictionaries

Array

Looks just like JS


var numbers = [1,2,3,4,5] // Mutable
let myNumbers = [6,7,8,9] // Immutable
                        

'numbers' is automatically typed as [Int]

Dictionaries

Stores key/value pairs in any order


let people = [ "first":"Kevin", "last":"Kazmierczak" ]
                        

'people' is automatically typed as [String:String]

Variables Playground

Control Flow

Conditionals and Loops

Conditionals

No parenthesis!?


var number = 10
if number < 10 {
    println("\(number) is less than 10")
}
                        

For Loops

Traditional loop


for var index = 0; index < 3; index++ {
    println(index)
}
                        

Range loop


for index in 1...5 {
    println(index)
}
                        

Collection Loops

Array loop


let numbers = [10,11,12,13]
for number in numbers {
    println(number)
}
                        

Dictionary loop


let people = [ "first":"Kevin", "last":"Kazmierczak" ]
for (key,value) in people {
    println("\(key) and \(value)")
}
                            

Control Flow Playground

Optionals

Learn them early to avoid annoyance later

Optional Values

Related to how we handle null/undefined in JS

You can tell if a variable will ever not have a value by type


var name:String?
                        

'name' is nil by default

Access the Optional

Optionals must be 'unwrapped' to access value

! unwraps an optional (Forced Unwrapping)


var name:String?
if name != nil {
    println(name!)
}
                        

Notice that ! is required to output the value

Optional Binding

Shorthand way to access optionals as a local constant


var name:String?
if let anotherName = name {
    println(anotherName)
} else {
    println('name was never defined')
}
                        

'anotherName' doesn't require an '!'

Implicitly Unwrapped Optionals

Variable will always have a value once set

Avoids using ! all the time to unwrap


var name:String! = "An optional name"
println(name) // Doesn't require an !
                        

Be careful of runtime errors

Super Shorthand


var optionalNumber = "43".toInt()
let fancyConversion = optionalNumber ?? 21 // is the same as doing
let notSoFancy = optionalNumber != nil ? optionalNumber! : 21
                        

Xcode is generally good at helping you with this

Use the quick help inspector to debug type issues

Optionals Playground

Functions

Simple Function

Uses crazy arrow to define return


func eatPizza(name:String) -> String {
    return "\(name) is eating pizza"
}
let pizzaMan = eatPizza("Kevin")
                        

Optional Returning Function

Use optional ? in return definition


func eatPizza(name:String) -> String? {
    if name == "Kevin" {
        return "\(name) is eating pizza"
    } else {
        return nil
    }
}
let pizzaMan = eatPizza("Bob") // returns nil
                        

'pizzaMan' is automatically typed as String?

Tuple Returning Function

Tuple is an ordered list of elements for complex returns


func getFullName() -> (first:String, last:String) {
    return ("Kevin", "Kazmierczak")
}
let name = getFullName().first // returns "Kevin"
                        

Function Playground

Classes

Simple Class

Defines an object to store data and provide functionality


class Person {
    var name = ""
    func getNamePreference() -> String {
        return "Kaz"
    }
}
let someGuy = Person()
someGuy.name = "Kevin"
let namePref = someGuy.getNamePreference()
                        

Subclassing


class Superhero: Person {
    var superpower = ""
}
let spiderman = Superhero()
spiderman.name = "Spiderman"
spiderman.superpower = "Webs"
                        

Properties

Custom getter/setters

Lazy properties

Property observers

Class Playground

Closures

Self contained blocks of code that capture variables in the current context


{ (PARAMETERS) -> RETURN in
    STATEMENTS
}
                        

Map Example

Map is a common function to map an array of values to a new array

JS Map (*not all browsers implement native map)


var names = ["Kevin", "Andrea", "Emily"]
var attendence = names.map( function( name ) {
    return name + " was here";
});
                            

Swift


var names = ["Kevin", "Andrea", "Emily"]
var attendence = names.map({ (name: String) -> String in
    return "\(name) is here"
})
                            

Closure Shorthand Magic


var names = ["Kevin", "Andrea", "Emily"]
var attendence = names.map({ (name: String) -> String in
    return "\(name) is here"
})
                        

can also be written as


var names = ["Kevin", "Andrea", "Emily"]
var attendence = names.map(){ "\($0) is here" }
                        

Referred to as Trailing Closure Syntax

$0 matches the first argument

But do I have to rewrite my app?

No, projects can mix languages

Uses a 'Bridging Header' to expose Obj-C files to Swift

Resources

My Apps

Madbombz

Download

FuelMate

Download

Battle Pet Galaxy

Download

Discussion