Swift

The language for the rest of us

2014 CodeImpact

Who am I

  • David Fekke
  • Develop on .NET, Node, Android and iOS
  • JaxNode User Group

Why another language

  • Apple needed a modern language
  • C++, C and Objective-C
  • Alternatives to Apple's tools have become popular

History of Apple modern development

  • Steve Jobs gets fired
  • Starts NeXT 1985
  • Objective-C
  • Chris Lattner joins Apple in 2005

Chris Lattner

  • Doctorial work on LLVM
  • He made improvements to Obj-C
  • Added properties
  • ARC memory management

Features taken from the most popular languages of the last 10 years

  • Python
  • C#
  • Javascript
  • Scala
  • Go
  • Rust

Swift

  • C without the overhead of C
  • type safe
  • uses type inference
  • parens not needed for loops or conditions
  • Don't need semicolons to end statements
  • no pointers needed

Functional

  • Has lots of functional features
  • Use let to make variable a constaint
  • use of closures common
  • functions inside of functions

Hello, World

  • var myText = "Hello World!"
  • println(myText)

Type notations

  • var x = "My string" // infers x will be a string
  • var y = 5 // infers value is a number
  • var z: Int = 4
  • var a: String = "My other string"
  • var myPrimes: [Int] = [1,2,3,5,7,11]
  • var myDict: [Int, String] = [1:"Some", 2:"Value"]
  • var myDict:Dictionary<Int,String> = [1:"Some", 2:"Value"]

Functions

func greet(name: String, day: String) -> String {
       return "Hello \(name), today is \(day)."
}
func sayHello() {
       println("Hello there.")
}
func sumOf(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
sumOf()
sumOf(42, 597, 12)

Closures and Lamdas

var numbers = [20, 19, 7, 12]

numbers.map({
    (number: Int) -> Int in
    let result = 3 * number
    return result
})

let sortedNumbers1 = sorted(numbers, { 
    (r1: Int, r2: Int) -> Bool in 
    return r1 > r2 } )

let sortedNumbers2 = sorted(numbers, { (r1, r2) in return r1 > r2 } )

let sortedNumbers3 = sorted(numbers) { $0 > $1 }

Classes

struct Resolution {
    var width = 0
    var height = 0
}
class VideoMode {
    var resolution = Resolution()
    var interlaced = false
    var frameRate = 0.0
    var name: String?
}

Inits and Functions

class Vehicle {
    var make: String?
    var model: String?
    var year: Int?
    
    init(val1: String, val2: String, val3: Int) {
        make = val1
        model = val2
        year = val3
    }
    
    func whatAmI() {
        println("I am a vehicle of make \(self.make) and model
                 \(self.model) of the year \(self.year)")
    }
}
let myVehic = Vehicle(val1: "Dodge", val2: "Charger", val3: 2007)
myVehic.whatAmI()

Inheritance

class Car: Vehicle {
    var wheels:Int = 4
    
    override init(val1: String, val2: String, val3: Int)
    {
        super.init(val1: val1, val2: val2, val3: val3)
    }
}

C# vs. Swift

// Declare Constant
// C#
const int legalAge = 18;
 
// Swift
let legalAge = 18
 
// Declare Variable
// C#
var legalAge = 18;
 
// Swift
var legalAge = 18

Type Annotation


// Declare Constant
// C#
const int legalAge = 18;
 
// Swift
let legalAge = 18
 
// Declare Variable
// C#
var legalAge = 18;
 
// Swift
var legalAge = 18

Type Inference

// Type Inference
// C#
var a = 3; // integer
var b = 0.14; // double
var c = a + b; // double
 
// Swift
var a = 3 // integer
var b = 0.14 // double
var c = a + b // double

Arrays

// Declare Arrays on single line
 
// String Array
// C#
var arr = new string[] { "One", "Two" };
 
// Swift
var arr = ["One", "Two"]
 
// Integer Array
// C#
var arr = new int[] { 1, 2 };
 
// Swift
var arr = [1, 2];

Arrays Cont.

// Iterating Over Array
// C#
foreach (var item in arr) {
    // do something
}
 
// Swift
for item in arr {
    // do something
}
 
 
// Get Item at Index
// C#
var item = arr[0];
// Swift
var item = arr[0]

Arrays Cont.

// Set Item at Index
// C#
arr[0] = "Value";
 
// Swift
arr[0] = "Value"
 
 
// Is Array Empty?
// C#
if (arr.Length == 0) {
    // array is empty
}
 
// Swift
if arr.isEmpty {
    // array is empty
}

Arrays Cont.

// Add Item to Array
// C#
Array.Resize(ref arr, arr.Length + 1);
arr[arr.Length - 1] = "Three";
 
// Swift
arr.append("Three")
// or
arr += "Three"
 
 
// Remove Item at Index
// C#
var list = arr.ToList();
list.RemoveAt(0);
var newArr = list.ToArray();
 
// Swift
var newArr = arr.removeAtIndex(0)

Declaring Dictionary

// Declaring Dictionaries
// C#
var dict = new Dictionary<string, string>();
var dict2 = new Dictionary<string, string>
{
    { "TYO", "Tokyo" },
    { "DUB", "Dublin" }
};
 
// Swift
var dict = Dictionary<String, String>()
var dict2 = ["TYO": "Tokyo", "DUB": "Dublin"]

Working w/ Dictionary

// Iterate over Dictionary
// C#
foreach(var item in dict) {
    var key = item.Key;
    var value = item.Value;
}
 
// Swift
for (key, value) in dict {
    // key variable contains key of item
    // value variable contains value of item
}
 
// Get Item in Dictionary by Key
// C#
var item = dict["TYO"];
 
// Swift
var item = dict["TYO"]

Dictionary Cont.

// Set Item in Dictionary by key
// or add if key doesn't exist
// C#
dict["LHR"] = "London";
 
// Swift
dict["LHR"] = "London"
 
 
// Remove Item in Dictionary by key
// C#
dict.Remove("LHR");
 
// Swift
dict.removeValueForKey("DUB")

For Loops

// Iterate from 1 through 5
// C#
// using increment
for(var i = 1; i <= 5; i++) {
    // do something with i
}
 
// Swift
// using range
for i in 1...5 {
    // do something with i
}
// using increment
for var i = 0; i <= 5; ++i {
    // do something with i
}

Conditional Statements

// If Then Else Conditional Statement
// C#
if (i > 6) {
    // do something
} else if (i > 3 && i <= 6) {
    // do something
} else {
    // do something
}
 
// Swift
if i > 6 {
    // do something
} else if i > 3 && i <= 6 {
    // do something
} else {
    // do something
}

Switch Statement

// Switch statement
// C#
var word = "A";
switch(word) {
    case "A":
        // do something
        break;
    case "B":
        // do something
        break;
    default:
        // do something
        break;
}
 
// Swift
var word = "A"
switch word {
    case "A":
        // do something
    case "B":
        // do something
    default:
        // do something
}

Switch Cont.

// Switch Case Ranges
// C#
switch (i) {
    case 1:
    case 2:
    case 3:
        // do something
        break;
    case 4:
        // do something
        break;
    default:
        // do something
        break;
}
 
// Swift
switch i {
    case 1...3:
        // do something
    case 4:
        // do something
    default:
        // do something
}

Functions

// Function with Parameter and Return Value
// C#
string sayHello(string name) {
    // do something
}
 
// Swift
func sayHello(name: String) -> String {
    // do something
}

DEMO

Other Swift Features

  • Optionals
  • Optional Chaining
  • enums syntax
  • structs syntax
  • switch statement does not require break

Resources

  • Free iBook from Apple
  • https://developer.apple.com/swift/blog/
  • https://developer.apple.com/swift/resources/
  • http://twitter.com/davidfekke

Questions

Contact me

  • David Fekke
  • Skype: davidfekke
  • email: david fekke at gmail dot com
  • twitter: @davidfekke