SWIFT
Introduction
o Introduced at Apple’s 2014 Worldwide Developer Conference
o Chris Lattner (LLVM, Clang)
o Current version 2.0
o Open source programminglanguage
o Objective-C, Rust, Haskell, Ruby, Python, C#, CLU…
o Compiled Programming Language
Why?
• Swift is easier to read
• Swift is easier to maintain
• Swift is safer
• Swift requires less code
• Swift is faster
• Swift supports dynamic libraries
• Swift Playgrounds encourages interactive coding
• Swift is a future you can influence
DIFFERENCES
• Header Files
• Brackets/Semicolons
• Ease of use
• Shorter syntax
• Clean classes
// objective c
#import "ViewController.h”
@implementationViewController // methods
@end
//Swift
class ViewController: UIViewController {
// propertiesand methods!
}
• Amount of code
// Objective C
@property (strong, nonatomic)IBOutlet UITextField *input;
@property (strong, nonatomic)IBOutlet UILabel *label;
[self.label setText:[NSString stringWithFormat:@"Welcome, %@", self.input.text]];
//Swift
@IBOutlet var input:UITextField!
@IBOutlet var label: UILabel!
label.text = "Welcome, (input.text)!"
CONSTANTS & VARIABLES
TYPE INFERENCE
let constant = 1 //readonly, cannot be re-assigned
constant = 2	// ERROR !!!
var variable = 1 // readwrite, can be re-assigned
variable = 2 // OK
//Type inference multiple variables
var variable1 = 1 , variable2 = 2, variable3 =3
- 'let' over 'var', when possible
TYPE ANNOTATIONS
let constant = 1
let constant: Int = 1 // no need for : Int
var variable: Int
variable = 1
// Type annotations multiple variables
var double1, double2, double3: Double
• UNICODE CHARACTERS IN CONSTANT & VARIABLE
NAMES
TYPE ALIASES
• DEFINE AN ALTERNATIVE NAME FOR AN EXISTING
TYPE
typealias SmallIntAlias = UInt16
• typedef double NSTimeInterval;
NUMBERS
INT, UINT, FLOAT & DOUBLE
var magic: Int = 42 // decimal
let pi: Double = 3.14 // 64-bit (default)
let pi: Float = 3.14 // 32-bit
• BOOLE AN
TRUE & FALSE
TUPLES
LIGHTWEIGHT, TEMPORARY CONTAINERS FOR
MULTIPLE VALUES
let myTuple= (1.0, -2.0) // CompoundType: (Double, Double)
let first= myTuple.0
let second=myTuple.1
OPTIONALS
AN OPTIONAL VALUE EITHER CONTAINS A VALUE OR
NIL
var optionalInt: Int? = 42
optionalInt = nil // to indicate that the value is missing
var optionalDouble: Double? // automatically sets to nil
// Check if nil
optionalDouble == nil
optionalDouble != nil
if newName != nil {!
print("His name is (newName!)")!
}
OPERATORS
• // Modulo Operator
3 % 2 // 1
• // Increment and Decrement Operator
i++; ++i; i--; --i
• // Compound Assignment Operator
i += 1 // i = i + 1
• // Logical Operator
a || b && c // equivalent to a || (b && c)
// Ternary Conditional Operator
(a == b ? 1 /* if true */ : 0 /* if false */)
• // Nil Coalescing Operator
a ?? b // a != nil ? a! : b
• // Closed Range Operator
0...2 // 0,1, 2
• // Half Open Range Operator
0..<2 // 0, 1
LOOPS
FOR[IN]
// old schoolc-style forloop
forvar index =0; index < 2; index++ { /* useindex */ }
// new iterator-style for-in loop
forvalue in 0..<2 { /* usevalue */ }
[DO] WHILE
// while evaluates itsexpression at the top of the loop
while x > 2 { /* */ }
// do-while evaluates its expression at the bottom of the loop
do {/* executed atleast once */} while x > 2
CONDITIONALS
IF-ELSE
let temperature = 40
var feverish: Bool
if temperature > 37 {
feverish = true
} else {
feverish = false
}
SWITCH
switch x { // break by default
case value1:
/* ... */
case value2, value3:
fallthrough// to not break
default:
/* ... */
} //
• SWITCH RANGE MATCHING
switch count {
case 0:
/* ...*/
case 1 ... 9:
/* ...*/
default:
/* ...*/
}
• SWITCH TUPLE MATCHING
switch point {
case (0,0):
/* ...*/
case (_,0):
/* ...*/
case (let x,1 ): // value binding
/* use x value */
default:
/* ...*/
}
• Supoorts string matching
PARENTHESES & BRACES
(Parentheses) are optional and by convention are often omitted
{Braces} are always required, even in one statement only
if temperature > 37 { feverish = true } // OK
if (temperature > 37) {feverish = true } // OK
if (temperature > 37) feverish = true // ERROR !!!
FUNCTIONS
• FIRST-CLASS FUNCTION
▸assign a function to variable
▸pass function as argument toanother function
▸return a function from a function
DECLARATION & CALL
• // With parameters and return value
funcfoo(parameter1: Type1,parameter1: Type2)-> ReturnType { /*
function body */ }
• foo(argument1, argument2) // call
• // Without parameters and return value
funcbar() -> Void { /* function body */}
funcbaz() -> () { /* function body */ }
funcquz() { /*function body */ }
quz() // call
EXTERNAL, LOCAL &
DEFAULT PARAMETERS// external and local parameter names
funcfoo(externalParameterName localParameterName: Type)
{
/* body use localParameterName */
}
foo(externalParameterName: argument) // callmust use externalParameterName
label
// # = shorthand for external parameter names
funcbar(#parameterName: Type) {/* body use parameterName */ }
bar(parameterName: argument) // call mustuse parameterName label
• // default parameter values
func baz(parameter1: Type1, parameterWithDefault: Int =
42) { /* ... */ }
baz(argument1) // call can omit value for
parameterWithDefault
• Closures are blocks of functionality that can be passed around
funcaddTwoInts(a: Int, b: Int) -> Int{
return a+ b
}
funcprintMathResult(mathFunction: (Int, Int) -> Int, a: Int, b:Int) {
println("Result: (mathFunction(a, b))")
}
printMathResult(addTwoInts, 3, 5)
ENUMERATIONS
• AN ENUMERATION DEFINES ACOMMON TYPE FOR A GROUPOF ITEMS
enum CellState {
caseAlive
caseDead
caseError
}
letstate1 = CellState.Alive;
letstate2 : CellState = .Dead
switch state1{
case.Alive:
/*... */
case.Dead:
/*... */
default:
/*... */
}
AN ENUMERATION ITEM CAN HAVE AN ASSOCIATED VALUE
enum CellState {
case Alive
case Dead
case Error(Int)// associated value can also bea tuple of values
}
leterrorState = CellState.Error(-1 );
// extract associated value as constantor variable
switch errorState {
case .Alive:
/*... */
case .Dead:
/*... */
case .Error(let errorCode): // ==case let .Error(errorCode)):
/*use errorCode */
}
• AN ENUMERATION ITEM CAN HAVE A RAW VALUE
enum CellState {
case Alive = 1
case Dead = 2
case Error = 3
}
enum CellState: Int { // Specify the Item Raw Value Type
case Alive = 1 , Dead, Error // Int auto-increment
}
let stateValue = CellState.Error.rawValue // 3
let aliveState: CellState? = CellState(rawValue: 1 ) //
CellState.Alive
STRUCTURES
• COPY VALUE ON ASSIGNMENTOR WHEN PASSED INTO
FUNCTION
// Structures are value types
struct CellPoint {
var x = 0.0
var y = 0.0
}
// Structures are always copied whenthey are passed around
var a = CellPoint(x: 1.0, y: 2.0); var b = a; b.x = 3.0;
a.x // 1.0 - a not changed
• MANY SWIFT LIBRARY'S BASE TYPES ARE
STRUCTURES
▸ String
▸ Character
▸ Array
▸ Dictionary
STRINGS & CHARACTERS
// String Declaration
var emptyString = "" // == var emptyString = String()
emptyString.isEmpty // true
let constString = "Hello"
// Character Declaration
var character: Character = "p"
forcharacter in "Hello" { // "H", "e", "l", "l", "o" }
// String Interpolation
let multiplier = 2
let message = "(multiplier) times 2.5 is (Double(multiplier) *
2.5)"
// Print a message in the std output
println(message)
// Comparing Strings
let str1 = "Hello"; let str2 = "Hello";
str1 == str2 // true
str1.hasPrefix("Hel") // true
str2.hasSuffix("llo") // true
ARRAYS
// Array Declaration
var emptyArray = [Int]() // Array<Int>()
var emptyArray : [Int] = []
var array = [25, 20, 16]
// Array Access: subscript out of boundsgenerate crash
array[1 ] // 20
array[1000]// RUNTIME ERROR !!!
array. count // 3
array.isEmpty // false
// Array Iteration
forvalue in array { /* use value*/ }
for(index, value) in enumerate(array) { /* use index and value */ }
VARIABLE ARRAYS
var variableArray = ["A"]
variableArray[0]= "A" // ["A"]
variableArray.append("B"); // ["A", "B"]
variableArray += ["C", "D"] // ["A", "B", "C", "D"]
variableArray.insert("Z", atIndex: 4) // ["A", "B", "C", "D", "Z”]
CONSTANT ARRAYS
let constantArray = ["A"]
constantArray = ["X"] // ERROR !!!
constantArray[0] = "Y" // ERROR !!!
constantArray.append("B"); // ERROR !!!
constantArray.removeAtIndex(0) // ERROR !!!
DICTIONARIES
// Dictionary Declaration
var emptyDictionary = [String, Int]() // Dictionary<String, Int>()
var emptyDictionary : [String, Int] = [:] // key : value
var dictionary = ["First" : 25, "Second" : 20, "Third" : 16]
// Dictionary Access: subscript return Optional
letsecond: Int? = dictionary["Second"] // .Some(20)
letlast: Int? = dictionary["Last"] // nil
dictionary.count // 3
dictionary.isEmpty// false
// Dictionary Iteration
for (key,value) in dictionary {/* use key andvalue */ }
dictionary.keys // [String]
dictionary.values // [Int]
VARIABLE DICTIONARIES
var variableDictionary = ["First" : 25]
variableDictionary =["Second" : 20] // ["Second" : 20]
variableDictionary["Third"] =16 // ["Second" : 20, "Third" : 16]
let oldKeyValue = variableDictionary.updateValue(18, forKey:
"Second”)
// oldValue => 20 //["Second" : 18, "Third" : 16]
// removes key
variableDictionary["Second"] = nil // ["Third" : 16]
CONSTANT DICTIONARIES
let constantDictionary = ["First" : 25, "Second" : 20, "Third" : 16]
constantDictionary = ["Last" : 0] // ERROR !!!
constantDictionary["Third"] = 15 // ERROR !!!
constantDictionary["Forth"] = 21 // ERROR !!!
constantDictionary["First"] = nil // ERROR !!!
CL ASSES
COPY REFERENCE ON ASSIGNMENT OR WHEN PASSED INTO
FUNCTION
//Classes are reference types
class Person {
var name: String?
var age: Int = 0
}
// Class reference (not object) are copied when they are passed around
var giuseppe = Person()
let joseph = giuseppe
joseph.name = "Joseph"
giuseppe.name// "Joseph”
INHERITANCE
AVAILABLEONLY FORCLASSES
// class Subclass:Superclass
classCar: Vehicle {
// override property
override var formattedName: String {
return "[car]" + name
}
// override method
override func order(){
// can call super.order()
}
}
FINAL CLASSES, PROPERTIES & METHODS
// Final class cannot be subclassed
final class Car : Vehicle { /* ... */ }
class Jeep : Car // ERROR !!!
class Bicycle : Vehicle {
// final property cannot be overridden
final var chainLength: Double
// final method cannot be overridden
final func pedal() { /* ... */}
}
INITIALIZATION
SETTINGINITIAL VALUES FOR STORED PROPERTIES
classCar {
letmodel: String
letwheels = 4
init() {
model = "Supercar"
}
}
// Initializers are called to create a new instance of a particular type with Type()syntax
letcar = Car()
car.model //"Supercar”
• INITIALIZATION PARAMETERS
class Car {
let model: String
init(model: String) {
self.model= model
}
}
// Initializers are called with external parameters
let car = Car(model: "Golf")
car.model // "Golf"
DEFAULT INITIALIZER
// Default Initializer are provided for class with no superclass or
structure
class Car {
var model = "Supercar"
let wheels = 4
}
let car = Car()
car.model // "Supercar"
EXTENSIONS
AVAILABLE FOR ENUMERATIONS, STRUCTURES &
CLASSES
EXTENSIONS CAN EXTEND ALSO SWIFT LIBRARY TYPES
SIMILAR TO CATEGORIES
PROTOCOLS
AVAILABLE FOR ENUMERATIONS, STRUCTURES & CLASSES
DELEGATION
protocolGameDelegate {
funcdidPlay(game:Game)
}
classGame {
var delegate: GameDelegate? // Optional delegate
funcplay() {
/* play */
delegate?.didPlay(self) //use Optional Chaining
}
}
PROTOCOLINHERITANCE
// A protocol can inherit one or moreother protocols
// and can add further requirements on top of the requirements it inherits
protocol BaseProtocol { func foo() }
protocol AnotherProtocol { func bar() }
// InheritingProtocol requires functions: foo, bar and baz
protocol InheritingProtocol: BaseProtocol, AnotherProtocol { funcbaz () }
classSomeClass: InheritingProtocol {
funcfoo() { /* ... */}
funcbar() { /* ... */ }
funcbaz() { /* ... */ }
}
ANYOBJECT
// AnyObject: any object of a class type
let instance: AnyObject = Car()
let car: Car = x as Car
let cars:[AnyObject] = [Car(), Car(), Car()] // see NSArray
forcar in cars as [Car] { /* use car: Car */ }
GENERICS
FUNCTIONS TYPES CAN BE GENERIC
▸ Generics avoid duplication and expresses its intent in the abstract
▸ Much of the Swift Library is built with generics (Array,
Dictionary)
▸ Type information is available at runtime
Final Words
• Same layout
• Swift is future
• Swift is still growing.(Not complete final product)
• Complexity in API not in language we use
• Objective C interoperability
Thank You

Swift - the future of iOS app development

  • 1.
  • 2.
    Introduction o Introduced atApple’s 2014 Worldwide Developer Conference o Chris Lattner (LLVM, Clang) o Current version 2.0 o Open source programminglanguage o Objective-C, Rust, Haskell, Ruby, Python, C#, CLU… o Compiled Programming Language
  • 3.
    Why? • Swift iseasier to read • Swift is easier to maintain • Swift is safer • Swift requires less code • Swift is faster • Swift supports dynamic libraries • Swift Playgrounds encourages interactive coding • Swift is a future you can influence
  • 5.
    DIFFERENCES • Header Files •Brackets/Semicolons • Ease of use • Shorter syntax • Clean classes // objective c #import "ViewController.h” @implementationViewController // methods @end //Swift class ViewController: UIViewController { // propertiesand methods! }
  • 6.
    • Amount ofcode // Objective C @property (strong, nonatomic)IBOutlet UITextField *input; @property (strong, nonatomic)IBOutlet UILabel *label; [self.label setText:[NSString stringWithFormat:@"Welcome, %@", self.input.text]]; //Swift @IBOutlet var input:UITextField! @IBOutlet var label: UILabel! label.text = "Welcome, (input.text)!"
  • 7.
  • 8.
    TYPE INFERENCE let constant= 1 //readonly, cannot be re-assigned constant = 2 // ERROR !!! var variable = 1 // readwrite, can be re-assigned variable = 2 // OK //Type inference multiple variables var variable1 = 1 , variable2 = 2, variable3 =3 - 'let' over 'var', when possible
  • 9.
    TYPE ANNOTATIONS let constant= 1 let constant: Int = 1 // no need for : Int var variable: Int variable = 1 // Type annotations multiple variables var double1, double2, double3: Double
  • 10.
    • UNICODE CHARACTERSIN CONSTANT & VARIABLE NAMES TYPE ALIASES • DEFINE AN ALTERNATIVE NAME FOR AN EXISTING TYPE typealias SmallIntAlias = UInt16 • typedef double NSTimeInterval;
  • 11.
    NUMBERS INT, UINT, FLOAT& DOUBLE var magic: Int = 42 // decimal let pi: Double = 3.14 // 64-bit (default) let pi: Float = 3.14 // 32-bit • BOOLE AN TRUE & FALSE
  • 12.
    TUPLES LIGHTWEIGHT, TEMPORARY CONTAINERSFOR MULTIPLE VALUES let myTuple= (1.0, -2.0) // CompoundType: (Double, Double) let first= myTuple.0 let second=myTuple.1
  • 13.
    OPTIONALS AN OPTIONAL VALUEEITHER CONTAINS A VALUE OR NIL var optionalInt: Int? = 42 optionalInt = nil // to indicate that the value is missing var optionalDouble: Double? // automatically sets to nil // Check if nil optionalDouble == nil optionalDouble != nil if newName != nil {! print("His name is (newName!)")! }
  • 14.
    OPERATORS • // ModuloOperator 3 % 2 // 1 • // Increment and Decrement Operator i++; ++i; i--; --i • // Compound Assignment Operator i += 1 // i = i + 1 • // Logical Operator a || b && c // equivalent to a || (b && c) // Ternary Conditional Operator (a == b ? 1 /* if true */ : 0 /* if false */) • // Nil Coalescing Operator a ?? b // a != nil ? a! : b • // Closed Range Operator 0...2 // 0,1, 2 • // Half Open Range Operator 0..<2 // 0, 1
  • 15.
    LOOPS FOR[IN] // old schoolc-styleforloop forvar index =0; index < 2; index++ { /* useindex */ } // new iterator-style for-in loop forvalue in 0..<2 { /* usevalue */ } [DO] WHILE // while evaluates itsexpression at the top of the loop while x > 2 { /* */ } // do-while evaluates its expression at the bottom of the loop do {/* executed atleast once */} while x > 2
  • 16.
    CONDITIONALS IF-ELSE let temperature =40 var feverish: Bool if temperature > 37 { feverish = true } else { feverish = false }
  • 17.
    SWITCH switch x {// break by default case value1: /* ... */ case value2, value3: fallthrough// to not break default: /* ... */ } //
  • 18.
    • SWITCH RANGEMATCHING switch count { case 0: /* ...*/ case 1 ... 9: /* ...*/ default: /* ...*/ } • SWITCH TUPLE MATCHING switch point { case (0,0): /* ...*/ case (_,0): /* ...*/ case (let x,1 ): // value binding /* use x value */ default: /* ...*/ } • Supoorts string matching
  • 19.
    PARENTHESES & BRACES (Parentheses)are optional and by convention are often omitted {Braces} are always required, even in one statement only if temperature > 37 { feverish = true } // OK if (temperature > 37) {feverish = true } // OK if (temperature > 37) feverish = true // ERROR !!!
  • 20.
    FUNCTIONS • FIRST-CLASS FUNCTION ▸assigna function to variable ▸pass function as argument toanother function ▸return a function from a function DECLARATION & CALL • // With parameters and return value funcfoo(parameter1: Type1,parameter1: Type2)-> ReturnType { /* function body */ } • foo(argument1, argument2) // call • // Without parameters and return value funcbar() -> Void { /* function body */} funcbaz() -> () { /* function body */ } funcquz() { /*function body */ } quz() // call
  • 21.
    EXTERNAL, LOCAL & DEFAULTPARAMETERS// external and local parameter names funcfoo(externalParameterName localParameterName: Type) { /* body use localParameterName */ } foo(externalParameterName: argument) // callmust use externalParameterName label // # = shorthand for external parameter names funcbar(#parameterName: Type) {/* body use parameterName */ } bar(parameterName: argument) // call mustuse parameterName label
  • 22.
    • // defaultparameter values func baz(parameter1: Type1, parameterWithDefault: Int = 42) { /* ... */ } baz(argument1) // call can omit value for parameterWithDefault • Closures are blocks of functionality that can be passed around
  • 23.
    funcaddTwoInts(a: Int, b:Int) -> Int{ return a+ b } funcprintMathResult(mathFunction: (Int, Int) -> Int, a: Int, b:Int) { println("Result: (mathFunction(a, b))") } printMathResult(addTwoInts, 3, 5)
  • 24.
    ENUMERATIONS • AN ENUMERATIONDEFINES ACOMMON TYPE FOR A GROUPOF ITEMS enum CellState { caseAlive caseDead caseError } letstate1 = CellState.Alive; letstate2 : CellState = .Dead switch state1{ case.Alive: /*... */ case.Dead: /*... */ default: /*... */ }
  • 25.
    AN ENUMERATION ITEMCAN HAVE AN ASSOCIATED VALUE enum CellState { case Alive case Dead case Error(Int)// associated value can also bea tuple of values } leterrorState = CellState.Error(-1 ); // extract associated value as constantor variable switch errorState { case .Alive: /*... */ case .Dead: /*... */ case .Error(let errorCode): // ==case let .Error(errorCode)): /*use errorCode */ }
  • 26.
    • AN ENUMERATIONITEM CAN HAVE A RAW VALUE enum CellState { case Alive = 1 case Dead = 2 case Error = 3 } enum CellState: Int { // Specify the Item Raw Value Type case Alive = 1 , Dead, Error // Int auto-increment } let stateValue = CellState.Error.rawValue // 3 let aliveState: CellState? = CellState(rawValue: 1 ) // CellState.Alive
  • 27.
    STRUCTURES • COPY VALUEON ASSIGNMENTOR WHEN PASSED INTO FUNCTION // Structures are value types struct CellPoint { var x = 0.0 var y = 0.0 } // Structures are always copied whenthey are passed around var a = CellPoint(x: 1.0, y: 2.0); var b = a; b.x = 3.0; a.x // 1.0 - a not changed
  • 28.
    • MANY SWIFTLIBRARY'S BASE TYPES ARE STRUCTURES ▸ String ▸ Character ▸ Array ▸ Dictionary
  • 29.
    STRINGS & CHARACTERS //String Declaration var emptyString = "" // == var emptyString = String() emptyString.isEmpty // true let constString = "Hello" // Character Declaration var character: Character = "p" forcharacter in "Hello" { // "H", "e", "l", "l", "o" }
  • 30.
    // String Interpolation letmultiplier = 2 let message = "(multiplier) times 2.5 is (Double(multiplier) * 2.5)" // Print a message in the std output println(message) // Comparing Strings let str1 = "Hello"; let str2 = "Hello"; str1 == str2 // true str1.hasPrefix("Hel") // true str2.hasSuffix("llo") // true
  • 31.
    ARRAYS // Array Declaration varemptyArray = [Int]() // Array<Int>() var emptyArray : [Int] = [] var array = [25, 20, 16] // Array Access: subscript out of boundsgenerate crash array[1 ] // 20 array[1000]// RUNTIME ERROR !!! array. count // 3 array.isEmpty // false // Array Iteration forvalue in array { /* use value*/ } for(index, value) in enumerate(array) { /* use index and value */ }
  • 32.
    VARIABLE ARRAYS var variableArray= ["A"] variableArray[0]= "A" // ["A"] variableArray.append("B"); // ["A", "B"] variableArray += ["C", "D"] // ["A", "B", "C", "D"] variableArray.insert("Z", atIndex: 4) // ["A", "B", "C", "D", "Z”]
  • 33.
    CONSTANT ARRAYS let constantArray= ["A"] constantArray = ["X"] // ERROR !!! constantArray[0] = "Y" // ERROR !!! constantArray.append("B"); // ERROR !!! constantArray.removeAtIndex(0) // ERROR !!!
  • 34.
    DICTIONARIES // Dictionary Declaration varemptyDictionary = [String, Int]() // Dictionary<String, Int>() var emptyDictionary : [String, Int] = [:] // key : value var dictionary = ["First" : 25, "Second" : 20, "Third" : 16] // Dictionary Access: subscript return Optional letsecond: Int? = dictionary["Second"] // .Some(20) letlast: Int? = dictionary["Last"] // nil dictionary.count // 3 dictionary.isEmpty// false // Dictionary Iteration for (key,value) in dictionary {/* use key andvalue */ } dictionary.keys // [String] dictionary.values // [Int]
  • 35.
    VARIABLE DICTIONARIES var variableDictionary= ["First" : 25] variableDictionary =["Second" : 20] // ["Second" : 20] variableDictionary["Third"] =16 // ["Second" : 20, "Third" : 16] let oldKeyValue = variableDictionary.updateValue(18, forKey: "Second”) // oldValue => 20 //["Second" : 18, "Third" : 16] // removes key variableDictionary["Second"] = nil // ["Third" : 16]
  • 36.
    CONSTANT DICTIONARIES let constantDictionary= ["First" : 25, "Second" : 20, "Third" : 16] constantDictionary = ["Last" : 0] // ERROR !!! constantDictionary["Third"] = 15 // ERROR !!! constantDictionary["Forth"] = 21 // ERROR !!! constantDictionary["First"] = nil // ERROR !!!
  • 37.
    CL ASSES COPY REFERENCEON ASSIGNMENT OR WHEN PASSED INTO FUNCTION //Classes are reference types class Person { var name: String? var age: Int = 0 } // Class reference (not object) are copied when they are passed around var giuseppe = Person() let joseph = giuseppe joseph.name = "Joseph" giuseppe.name// "Joseph”
  • 38.
    INHERITANCE AVAILABLEONLY FORCLASSES // classSubclass:Superclass classCar: Vehicle { // override property override var formattedName: String { return "[car]" + name } // override method override func order(){ // can call super.order() } }
  • 39.
    FINAL CLASSES, PROPERTIES& METHODS // Final class cannot be subclassed final class Car : Vehicle { /* ... */ } class Jeep : Car // ERROR !!! class Bicycle : Vehicle { // final property cannot be overridden final var chainLength: Double // final method cannot be overridden final func pedal() { /* ... */} }
  • 40.
    INITIALIZATION SETTINGINITIAL VALUES FORSTORED PROPERTIES classCar { letmodel: String letwheels = 4 init() { model = "Supercar" } } // Initializers are called to create a new instance of a particular type with Type()syntax letcar = Car() car.model //"Supercar”
  • 41.
    • INITIALIZATION PARAMETERS classCar { let model: String init(model: String) { self.model= model } } // Initializers are called with external parameters let car = Car(model: "Golf") car.model // "Golf"
  • 42.
    DEFAULT INITIALIZER // DefaultInitializer are provided for class with no superclass or structure class Car { var model = "Supercar" let wheels = 4 } let car = Car() car.model // "Supercar"
  • 43.
    EXTENSIONS AVAILABLE FOR ENUMERATIONS,STRUCTURES & CLASSES EXTENSIONS CAN EXTEND ALSO SWIFT LIBRARY TYPES SIMILAR TO CATEGORIES
  • 44.
    PROTOCOLS AVAILABLE FOR ENUMERATIONS,STRUCTURES & CLASSES DELEGATION protocolGameDelegate { funcdidPlay(game:Game) } classGame { var delegate: GameDelegate? // Optional delegate funcplay() { /* play */ delegate?.didPlay(self) //use Optional Chaining } }
  • 45.
    PROTOCOLINHERITANCE // A protocolcan inherit one or moreother protocols // and can add further requirements on top of the requirements it inherits protocol BaseProtocol { func foo() } protocol AnotherProtocol { func bar() } // InheritingProtocol requires functions: foo, bar and baz protocol InheritingProtocol: BaseProtocol, AnotherProtocol { funcbaz () } classSomeClass: InheritingProtocol { funcfoo() { /* ... */} funcbar() { /* ... */ } funcbaz() { /* ... */ } }
  • 46.
    ANYOBJECT // AnyObject: anyobject of a class type let instance: AnyObject = Car() let car: Car = x as Car let cars:[AnyObject] = [Car(), Car(), Car()] // see NSArray forcar in cars as [Car] { /* use car: Car */ }
  • 47.
    GENERICS FUNCTIONS TYPES CANBE GENERIC ▸ Generics avoid duplication and expresses its intent in the abstract ▸ Much of the Swift Library is built with generics (Array, Dictionary) ▸ Type information is available at runtime
  • 49.
    Final Words • Samelayout • Swift is future • Swift is still growing.(Not complete final product) • Complexity in API not in language we use • Objective C interoperability
  • 50.