SlideShare a Scribd company logo
IOS BOOTCAMP
7° EDITION
#pragma mark
@ WCAP Catania
06/06/2015, v 1.2-S
THANKS TO
Youthub Catania
Motorsquare
#PRAGMA MARK
Started by a group of friends in 2012
Aim: create a community of iOS developers
Non-profit org since Sept. 2013
#PRAGMA MARK
In 3 years:
Organized a dozen events in northern Italy
all over Italy! !
Created an active on-line community:
fb.com/groups/pragmamark
2 editions of the #Pragma Conference
#PRAGMA MARK
Next edition: Florence, 9-10 Oct 2015
www.pragmaconference.com
JUST FOR TODAY'S ATTENDEES
15% DISCOUNT CODE:
! PragmaLovesCatania "
(limited to 30 tickets, so be quick!)
LET'S GET THE
BOOTCAMP STARTED!
HELLO WORLD
▸ Matteo Battaglio
▸ iOS dev @ Codermine
▸ #pragma mark co-founder
SLIDES
http://bit.ly/swift-introduction
HISTORY
LANGUAGE FATHER
Chris Lattner
LANGUAGE BIRTH
I started work on the Swift Programming Language in July
of 2010. I implemented much of the basic language
structure, with only a few people knowing of its
existence. A few other (amazing) people started
contributing in earnest late in 2011, and it became a
major focus for the Apple Developer Tools group in July
2013.
— Chris Lattner
LANGUAGE INSPIRATION
The Swift Programming Language greatly benefited from
the experiences hard-won by many other languages in the
field, drawing ideas from Objective-C, Rust, Haskell, Ruby,
Python, C#, CLU, and far too many others to list.
— Chris Lattner
PRINCIPLES
SWIFT PROGRAMMING LANGUAGE
imperative, functional, object oriented, multi-paradigm,
static, strong typed, type safe, inferred,
general purpose, compiled, fast,
modern, elegant, clean,
funny, happy,
❤
SYNTAX
Immutable & Mutable
Functions & Closures
Tuples & Pattern Matching
Data Types & Instances
Protocols & Extensions
Generics & Optionals
IMMUTABLE & MUTABLE
CONSTANTS & VARIABLES
TYPE ANNOTATIONS & TYPE INFERENCE
let constant: Int = 1 // Type Annotations
let constant = 1 // Type Inference (as Int)
let constant = 1 // readonly, cannot be re-assigned
constant = 2 // ❌ ERROR !!!
var variable = 1 // readwrite, can be re-assigned
variable = 2 // OK
By convention you should prefer to use 'let' over 'var'
CONSTANTS & VARIABLES
UNICODE CHARACTERS IN CONSTANT & VARIABLE NAMES
let !!!! = 4
var """"" = 5
! KILLER APPLICATION "
VALUE & REFERENCE TYPES
ENUMERATIONS & STRUCTURES VS CLASSES
▸ Enumerations & Structures are passed by Value
▸ Classes are passed by Reference
ENUMERATIONS & STRUCTURES ARE ALWAYS COPIED WHEN THEY ARE PASSED
AROUND IN THE CODE, AND DO NOT USE REFERENCE COUNTING.
STRUCTURES
MANY SWIFT LIBRARY'S BASE TYPES ARE STRUCTURES
// String
let string = "Swift"
// Character
let character: Character = "c"
// Array
let array = ["A", "B"]
// Dictionary
let dictionary = ["First" : 1, "Second" : 2]
STRUCTURES
CONSTANT & VARIABLE ARRAYS
let constantArray = ["A"]
var variableArray = ["A"]
constantArray = ["X"] // ❌ ERROR !!!
constantArray[0] = "Y" // ❌ ERROR !!!
constantArray.append("B"); // ❌ ERROR !!!
constantArray.removeAtIndex(0) // ❌ ERROR !!!
variableArray = ["X"] // ["X"]
variableArray[0] = "A" // ["A"]
variableArray.append("B"); // ["A", "B"]
variableArray.removeAtIndex(0) // ["B"]
FUNCTIONS & CLOSURES
FUNCTIONS
FIRST-CLASS FUNCTION
▸ assign a function to variable
▸ pass function as argument to another function
▸ return a function from a function
▸ functional programming patterns: map, filter, ...
FUNCTIONS
DECLARATION & CALL
// declaration
func foo(parameter1: Type1, parameter1: Type2) -> ReturnType {
/* function body */
}
// call
foo(argument1, argument2)
// external and local parameter names
func bar(externalParameterName localParameterName: Type) {
/* body use localParameterName */
}
// call must use externalParameterName label
bar(externalParameterName: argument)
CLOSURES
MEANING & SYNTAX
// Closures are blocks of functionality that can be passed around
{ (parameter1: Type1, parameter2: Type2) -> ReturnType in
/ * ... */
}
// Closures can capture and store references to any constants and
// variables from the context in which they are defined.
FUNCTIONS VS CLOSURES
▸ Global functions:
NAMED CLOSURES / DO NOT CAPTURE ANY VALUES
▸ Nested functions:
NAMED CLOSURES / CAPTURE VALUES FROM ENCLOSING FUNCTION
▸ Closure expressions:
UNNAMED CLOSURES / CAPTURE VALUES FROM THEIR CONTEXT
FUNCTIONS VS CLOSURES
SORTING WITHOUT CLOSURES
// define a function which takes an array and a sorting algorithm
func sorted(array: [Int], algorithm: (Int, Int) -> Bool) -> [Int] {
/* apply the sorting algorithm to the array */
}
// define an array
let array = [1, 2, 3]
// define a sorting algorithm funtion
func backwards(i1: Int, i2: Int) {
return i1 > i2
}
// call sorted
var reversed = sorted(array, backwards)
FUNCTIONS VS CLOSURES
SORTING WITH CLOSURES 1/2
// Fully declared closure
reversed = sorted(array, { (i1: Int, i2: Int) -> Bool in return i1 > i2 } )
// Infer closure type
reversed = sorted(array, { (i1, i2) in return i1 > i2 } )
// Implicit returns
reversed = sorted(array, { (i1, i2) in i1 > i2 } )
FUNCTIONS VS CLOSURES
SORTING WITH CLOSURES 2/2
// Shorthand argument names
reversed = sorted(array, { $0 > $1 } )
// Trailing closure: outside of () only if it's function’s final argument
reversed = sorted(array) { $0 > $1 }
// Operator functions
reversed = sorted(array, >)
TUPLES & PATTERN MATCHING
TUPLES
LIGHTWEIGHT CONTAINERS FOR MULTIPLE VALUES
let complex = (1.0, -2.0) // Compound Type: (Double, Double)
let (real, imag) = complex // Decompose
let (real, _) = complex // Underscores ignore value
// Access by index
let real = complex.0
let imag = complex.1
// Name elements
let complex = (real: 1.0, imag: -2.0)
let real = complex.real
PATTERN MATCHING
let point = (42, 42)
switch point { // break by default
case (0, 0):
println("match a specific tuple")
case (_, 0):
println("ignore undescore value")
case (let x, 1):
println("bind a value to x")
case let (x, y) where x == y:
println("bind values which satify the where clause")
default:
println("must be exhaustive")
}
DATA TYPES & INSTANCES
ENUMERATIONS, STRUCTURES & CLASSES
COMMON CAPABILITIES
▸ Stored & Computed Properties
▸ Methods, Subscripts & Initializers
▸ Protocols & Extensions
▸ Access Control
ENUMERATIONS, STRUCTURES & CLASSES
public class Vehicle {
// stored instance property
private let name: String
// computed instance property
public var formattedName: String { return "vehicle: (name)" }
// type property
class var maxSpeed : Int { return 299_792_458 }
// initializer
init (name: String) { self.name = name }
// instance method
internal func move() { /* ... */ }
}
CLASSES Only
ADDITIONAL CAPABILITIES:
▸ Inheritance
▸ Type casting
▸ Deinitializers
▸ Reference counting
CLASSES Only
public class Car: Vehicle { // inheritance
// override
public override var formattedName: String { return "car: (name)" }
// designated initializer
override init(name: String) { super.init(name: name);}
// convenience initializer
convenience init() { self.init(name: "Car") }
// deinitializer
deinit { /* clean up */ }
}
let vehicle = Car(name: "Supercar")
let car = vehicle as Car // Type Casting
PROTOCOLS & EXTENSIONS
PROTOCOLS
// Available for Enumerations, Structures & Classes
protocol SomeProtocol { // define a set of requirements
var instanceProperty: Type { get set } // require instance properties
class var typeProperty: Type { get set } // require type properties
func someMethod() // require instance methods
class func someTypeMethod() // require type methods
init() // require initializers
}
EXTENSIONS
// Available for Enumerations, Structures & Classes
extension SomeType: SomeProtocol { // add protocol conformance
var stored = 1 // ❌ ERROR !!! // CANNOT add store properties !
var computed: String { /* ... */ } // add computed properties
func method() { /* ... */ } // add methods
subscript(i: Int) -> String { /* ... */ } // add subscripts
init(parameter: Type) { /* ... */ } // add initializers
enum SomeEnum { /* ... */ } // add nested types
}
EXTENSIONS
EXTENSIONS CAN EXTEND ALSO SWIFT LIBRARY TYPES
extension Int {
func times(task: () -> ()) {
for i in 0 ..< self {
task()
}
}
}
3.times({ println("Developer! ") })
// Developer! Developer! Developer! !
GENERICS & OPTIONALS
GENERICS
// Specific Functions
func swapTwoStrings(inout a: String, inout b: String) {
let temporaryA = a; a = b; b = temporaryA
}
func swapTwoDoubles(inout a: Double, inout b: Double) {
let temporaryA = a; a = b; b = temporaryA
}
// Generic Function
func swapTwoValues<T>(inout a: T, inout b: T) {
let temporaryA = a; a = b; b = temporaryA
}
var someInt = 1, anotherInt = 2
swapTwoValues(&someInt, &anotherInt) // T == Int
// someInt == 2, anotherInt == 1
GENERICS
WHERE CLAUSES ON TYPE CONSTRAINTS
protocol Container { typealias ItemType /* ... */ }
func allItemsMatch<
C1: Container, C2: Container
where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>
(container1: C1, container2: C2) -> Bool {
if container1.count != container2.count { return false }
for i in 0..<container1.count {
if container1[i] != container2[i] {
return false
}
}
return true // all items match
}
}
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
OPTIONALS
// Force unwrap
let optionalInt: Int? = 42
let definitelyInt = optionalInt! // throws runtime error if nil
// Optional binding
if let definitelyInt = optionalInt {
// runs if optionalInt is not nil and sets definitelyInt: Int
}
// Implicitly Unwrapped Optionals
var assumedInt: Int! // set to nil
assumedInt = 42
var implicitInt: Int = assumedInt // do not need an exclamation mark
assumedInt = nil
implicitInt = assumedInt // ❌ RUNTIME ERROR !!!
OPTIONALS
class Car {
var model: String
init(model: String) { self.model = model }
func jump() -> String? {
if model == "Supercar" { return "!⚡" }
else { return nil } }
}
// Return type of chaining is always optional
var car1: Car? = nil; car1?.model // nil: String?
var car2: Car? = Car(model: "Supercar"); car2?.model // "Supercar": String?
// Chain on optional return value
car1?.jump()?.hasPrefix("!") // type Bool?
OPTIONALS
A GENERIC ENUMERATION WITH ASSOCIATED VALUE
enum Optional<T> : Reflectable, NilLiteralConvertible {
case None
case Some(T)
/* ... */
}
var maybeInt1: Int? = nil
var maybeInt2: Optional<Int> = .None
maybeInt1 = 42
maybeInt2 = .Some(42)
FINAL
THOUGHTS
SWIFT VS ... ?
▸ Swift vs Scala
▸ Swift vs Rust
▸ Swift vs C#
Swift is Objective-C without the C
OPEN SOURCE SWIFT ?
Guys, feel free to make up your own dragons if you want,
but your speculation is just that: speculation. We literally
have not even discussed this yet, because we have a ton
of work to do [...] You can imagine that many of us want it
to be open source and part of llvm, but the discussion
hasn't happened yet, and won't for some time.
— Chris Lattner @ llvmdev
WHAT SWIFT IS MISSING?
[ SWIFT 1.2 IN XCODE 6.3 ]
▸ Compiler attributes and Preprocessor
▸ Exceptions, KVO, KVC and proper Reflection
HTTPS://GITHUB.COM/KSM/SWIFTINFLUX
SWIFT IN PRODUCTION?
▸ Companies are doing it
▸ Freelances are doing it
▸ Many of us are doing it
▸ But be careful if you do it!
A few apps that were built using Swift @ apple.com
WWDC
next week (8-12 June)
Great expectations for Swift...
THANKSYou can find me on the Internet!
twitter ! @m4dbat
github ! madbat
" matteo.battaglio@pragmamark.org

More Related Content

What's hot

Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
Michele Titolo
 
SWIFT 3
SWIFT 3SWIFT 3
SWIFT 3
Chuong Huynh
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
Aleš Najmann
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
Tran Khoa
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
Swift Programming - Part 2
Swift Programming - Part 2Swift Programming - Part 2
Swift Programming - Part 2
Mindfire Solutions
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
Swift Bengaluru Meetup slides
Swift Bengaluru Meetup slidesSwift Bengaluru Meetup slides
Swift Bengaluru Meetup slides
Pushkar Kulkarni
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
msemenistyi
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
T11 Sessions
 
C++ Quick Reference Sheet from Hoomanb.com
C++ Quick Reference Sheet from Hoomanb.comC++ Quick Reference Sheet from Hoomanb.com
C++ Quick Reference Sheet from Hoomanb.com
FrescatiStory
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
Bunlong Van
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Bui Kiet
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-C
Kazunobu Tasaka
 
BASIC C++ PROGRAMMING
BASIC C++ PROGRAMMINGBASIC C++ PROGRAMMING
BASIC C++ PROGRAMMING
gufranresearcher
 
Javascript
JavascriptJavascript
Javascript
theacadian
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
Swift 2
Swift 2Swift 2
Swift 2
Jens Ravens
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 

What's hot (20)

Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
 
SWIFT 3
SWIFT 3SWIFT 3
SWIFT 3
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Swift Programming - Part 2
Swift Programming - Part 2Swift Programming - Part 2
Swift Programming - Part 2
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Swift Bengaluru Meetup slides
Swift Bengaluru Meetup slidesSwift Bengaluru Meetup slides
Swift Bengaluru Meetup slides
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
C++ Quick Reference Sheet from Hoomanb.com
C++ Quick Reference Sheet from Hoomanb.comC++ Quick Reference Sheet from Hoomanb.com
C++ Quick Reference Sheet from Hoomanb.com
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-C
 
BASIC C++ PROGRAMMING
BASIC C++ PROGRAMMINGBASIC C++ PROGRAMMING
BASIC C++ PROGRAMMING
 
Javascript
JavascriptJavascript
Javascript
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Swift 2
Swift 2Swift 2
Swift 2
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 

Viewers also liked

Barometrul antreprenoriatului romanesc 2012
Barometrul antreprenoriatului romanesc 2012Barometrul antreprenoriatului romanesc 2012
Barometrul antreprenoriatului romanesc 2012
Mihaela Matei
 
lyleresume2015-2
lyleresume2015-2lyleresume2015-2
lyleresume2015-2
Janet Lyle
 
Responsive Design for the Web
Responsive Design for the WebResponsive Design for the Web
Responsive Design for the Web
jonbuda
 
#CannesLions 2014: Day 1 Recap #OgilvyCannes
#CannesLions 2014: Day 1 Recap #OgilvyCannes#CannesLions 2014: Day 1 Recap #OgilvyCannes
#CannesLions 2014: Day 1 Recap #OgilvyCannes
Ogilvy
 
Semantic Web Intro - St. Patrick's Day 2016 Update
Semantic Web Intro - St. Patrick's Day 2016 UpdateSemantic Web Intro - St. Patrick's Day 2016 Update
Semantic Web Intro - St. Patrick's Day 2016 Update
Eric Franzon
 
Grecia
GreciaGrecia
Programa semana da leitura 2011
Programa semana da leitura 2011Programa semana da leitura 2011
Programa semana da leitura 2011
Fernanda Gonçalves
 
Top 10 Famous Motivational Speakers
Top 10 Famous Motivational SpeakersTop 10 Famous Motivational Speakers
Top 10 Famous Motivational Speakers
Eagles Talent Speakers Bureau
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
Andres Almiray
 
Eu and turkey challenges and opportunities by emanuel baisire
Eu and turkey challenges and opportunities by emanuel baisireEu and turkey challenges and opportunities by emanuel baisire
Eu and turkey challenges and opportunities by emanuel baisire
Emanuel Baisire
 
eMarketer Webinar: 7 Social Media Ad Trends for 2014
eMarketer Webinar: 7 Social Media Ad Trends for 2014eMarketer Webinar: 7 Social Media Ad Trends for 2014
eMarketer Webinar: 7 Social Media Ad Trends for 2014
eMarketer
 
Lessons Learned with Cassandra and Spark at the US Patent and Trademark Office
Lessons Learned with Cassandra and Spark at the US Patent and Trademark OfficeLessons Learned with Cassandra and Spark at the US Patent and Trademark Office
Lessons Learned with Cassandra and Spark at the US Patent and Trademark Office
DataStax Academy
 

Viewers also liked (13)

Barometrul antreprenoriatului romanesc 2012
Barometrul antreprenoriatului romanesc 2012Barometrul antreprenoriatului romanesc 2012
Barometrul antreprenoriatului romanesc 2012
 
lyleresume2015-2
lyleresume2015-2lyleresume2015-2
lyleresume2015-2
 
Responsive Design for the Web
Responsive Design for the WebResponsive Design for the Web
Responsive Design for the Web
 
#CannesLions 2014: Day 1 Recap #OgilvyCannes
#CannesLions 2014: Day 1 Recap #OgilvyCannes#CannesLions 2014: Day 1 Recap #OgilvyCannes
#CannesLions 2014: Day 1 Recap #OgilvyCannes
 
Semantic Web Intro - St. Patrick's Day 2016 Update
Semantic Web Intro - St. Patrick's Day 2016 UpdateSemantic Web Intro - St. Patrick's Day 2016 Update
Semantic Web Intro - St. Patrick's Day 2016 Update
 
Grecia
GreciaGrecia
Grecia
 
Programa semana da leitura 2011
Programa semana da leitura 2011Programa semana da leitura 2011
Programa semana da leitura 2011
 
3
33
3
 
Top 10 Famous Motivational Speakers
Top 10 Famous Motivational SpeakersTop 10 Famous Motivational Speakers
Top 10 Famous Motivational Speakers
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Eu and turkey challenges and opportunities by emanuel baisire
Eu and turkey challenges and opportunities by emanuel baisireEu and turkey challenges and opportunities by emanuel baisire
Eu and turkey challenges and opportunities by emanuel baisire
 
eMarketer Webinar: 7 Social Media Ad Trends for 2014
eMarketer Webinar: 7 Social Media Ad Trends for 2014eMarketer Webinar: 7 Social Media Ad Trends for 2014
eMarketer Webinar: 7 Social Media Ad Trends for 2014
 
Lessons Learned with Cassandra and Spark at the US Patent and Trademark Office
Lessons Learned with Cassandra and Spark at the US Patent and Trademark OfficeLessons Learned with Cassandra and Spark at the US Patent and Trademark Office
Lessons Learned with Cassandra and Spark at the US Patent and Trademark Office
 

Similar to Introduction to Swift

Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
Giuseppe Arici
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdf
Spam92
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
Jari Abbas
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
RameshNair6
 
Templates
TemplatesTemplates
Templates
Farwa Ansari
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
Santosh Rajan
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
Intelligo Technologies
 
Clean code slide
Clean code slideClean code slide
Clean code slide
Anh Huan Miu
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
Kazunobu Tasaka
 
Practical Meta Programming
Practical Meta ProgrammingPractical Meta Programming
Practical Meta Programming
Reggie Meisler
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
Nico Ludwig
 
What is storage class
What is storage classWhat is storage class
What is storage class
Isha Aggarwal
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
Jesse Talavera-Greenberg
 
C++ Boot Camp Part 1
C++ Boot Camp Part 1C++ Boot Camp Part 1
C++ Boot Camp Part 1
Jesse Talavera-Greenberg
 
Namespaces
NamespacesNamespaces
Namespaces
zindadili
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
Iwan van der Kleijn
 
The Ring programming language version 1.10 book - Part 97 of 212
The Ring programming language version 1.10 book - Part 97 of 212The Ring programming language version 1.10 book - Part 97 of 212
The Ring programming language version 1.10 book - Part 97 of 212
Mahmoud Samir Fayed
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptx
MrMudassir
 

Similar to Introduction to Swift (20)

Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdf
 
C++ Functions
C++ FunctionsC++ Functions
C++ Functions
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 
Templates
TemplatesTemplates
Templates
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
Practical Meta Programming
Practical Meta ProgrammingPractical Meta Programming
Practical Meta Programming
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
What is storage class
What is storage classWhat is storage class
What is storage class
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
C++ boot camp part 1/2
C++ boot camp part 1/2C++ boot camp part 1/2
C++ boot camp part 1/2
 
C++ Boot Camp Part 1
C++ Boot Camp Part 1C++ Boot Camp Part 1
C++ Boot Camp Part 1
 
Namespaces
NamespacesNamespaces
Namespaces
 
Type script - advanced usage and practices
Type script  - advanced usage and practicesType script  - advanced usage and practices
Type script - advanced usage and practices
 
The Ring programming language version 1.10 book - Part 97 of 212
The Ring programming language version 1.10 book - Part 97 of 212The Ring programming language version 1.10 book - Part 97 of 212
The Ring programming language version 1.10 book - Part 97 of 212
 
Oop lect3.pptx
Oop lect3.pptxOop lect3.pptx
Oop lect3.pptx
 

Recently uploaded

CrushFTP 10.4.0.29 PC Software - WhizNews
CrushFTP 10.4.0.29 PC Software - WhizNewsCrushFTP 10.4.0.29 PC Software - WhizNews
CrushFTP 10.4.0.29 PC Software - WhizNews
Eman Nisar
 
A Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdf
A Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdfA Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdf
A Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdf
kalichargn70th171
 
Test Polarity: Detecting Positive and Negative Tests (FSE 2024)
Test Polarity: Detecting Positive and Negative Tests (FSE 2024)Test Polarity: Detecting Positive and Negative Tests (FSE 2024)
Test Polarity: Detecting Positive and Negative Tests (FSE 2024)
andrehoraa
 
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdfAI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
Daniel Zivkovic
 
BDRSuite - #1 Cost effective Data Backup and Recovery Solution
BDRSuite - #1 Cost effective Data Backup and Recovery SolutionBDRSuite - #1 Cost effective Data Backup and Recovery Solution
BDRSuite - #1 Cost effective Data Backup and Recovery Solution
praveene26
 
AI-driven Automation_ Transforming DevOps Practices.docx
AI-driven Automation_ Transforming DevOps Practices.docxAI-driven Automation_ Transforming DevOps Practices.docx
AI-driven Automation_ Transforming DevOps Practices.docx
zoondiacom
 
How to Secure Your Kubernetes Software Supply Chain at Scale
How to Secure Your Kubernetes Software Supply Chain at ScaleHow to Secure Your Kubernetes Software Supply Chain at Scale
How to Secure Your Kubernetes Software Supply Chain at Scale
Anchore
 
Generative AI The Key to Smarter, Faster IT Development.pdf
Generative AI The Key to Smarter, Faster IT Development.pdfGenerative AI The Key to Smarter, Faster IT Development.pdf
Generative AI The Key to Smarter, Faster IT Development.pdf
ayushiqss
 
05. Ruby Control Structures - Ruby Core Teaching
05. Ruby Control Structures - Ruby Core Teaching05. Ruby Control Structures - Ruby Core Teaching
05. Ruby Control Structures - Ruby Core Teaching
quanhoangd129
 
Waze vs. Google Maps vs. Apple Maps, Who Else.pdf
Waze vs. Google Maps vs. Apple Maps, Who Else.pdfWaze vs. Google Maps vs. Apple Maps, Who Else.pdf
Waze vs. Google Maps vs. Apple Maps, Who Else.pdf
Ben Ramedani
 
Applitools Autonomous 2.0 Sneak Peek.pdf
Applitools Autonomous 2.0 Sneak Peek.pdfApplitools Autonomous 2.0 Sneak Peek.pdf
Applitools Autonomous 2.0 Sneak Peek.pdf
Applitools
 
Three available editions of Windows Servers crucial to your organization’s op...
Three available editions of Windows Servers crucial to your organization’s op...Three available editions of Windows Servers crucial to your organization’s op...
Three available editions of Windows Servers crucial to your organization’s op...
Q-Advise
 
New York University degree Cert offer diploma Transcripta
New York University degree Cert offer diploma Transcripta New York University degree Cert offer diploma Transcripta
New York University degree Cert offer diploma Transcripta
pyxgy
 
Empowering Businesses with Intelligent Software Solutions - Grawlix
Empowering Businesses with Intelligent Software Solutions - GrawlixEmpowering Businesses with Intelligent Software Solutions - Grawlix
Empowering Businesses with Intelligent Software Solutions - Grawlix
Aarisha Shaikh
 
pgroll - Zero-downtime, reversible, schema migrations for Postgres
pgroll - Zero-downtime, reversible, schema migrations for Postgrespgroll - Zero-downtime, reversible, schema migrations for Postgres
pgroll - Zero-downtime, reversible, schema migrations for Postgres
Tudor Golubenco
 
Unlocking the Future of Artificial Intelligence
Unlocking the Future of Artificial IntelligenceUnlocking the Future of Artificial Intelligence
Unlocking the Future of Artificial Intelligence
dorinIonescu
 
Unlocking value with event-driven architecture by Confluent
Unlocking value with event-driven architecture by ConfluentUnlocking value with event-driven architecture by Confluent
Unlocking value with event-driven architecture by Confluent
confluent
 
Mlm software - Binary, Board, Matrix, Monoline, Unilevel MLM Ecommerce or E-p...
Mlm software - Binary, Board, Matrix, Monoline, Unilevel MLM Ecommerce or E-p...Mlm software - Binary, Board, Matrix, Monoline, Unilevel MLM Ecommerce or E-p...
Mlm software - Binary, Board, Matrix, Monoline, Unilevel MLM Ecommerce or E-p...
LETSCMS Private Limited
 
vSAN_Tutorial_Presentation with important topics
vSAN_Tutorial_Presentation with important  topicsvSAN_Tutorial_Presentation with important  topics
vSAN_Tutorial_Presentation with important topics
abhilashspt
 
Bring Strategic Portfolio Management to Monday.com using OnePlan - Webinar 18...
Bring Strategic Portfolio Management to Monday.com using OnePlan - Webinar 18...Bring Strategic Portfolio Management to Monday.com using OnePlan - Webinar 18...
Bring Strategic Portfolio Management to Monday.com using OnePlan - Webinar 18...
OnePlan Solutions
 

Recently uploaded (20)

CrushFTP 10.4.0.29 PC Software - WhizNews
CrushFTP 10.4.0.29 PC Software - WhizNewsCrushFTP 10.4.0.29 PC Software - WhizNews
CrushFTP 10.4.0.29 PC Software - WhizNews
 
A Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdf
A Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdfA Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdf
A Step-by-Step Guide to Selecting the Right Automated Software Testing Tools.pdf
 
Test Polarity: Detecting Positive and Negative Tests (FSE 2024)
Test Polarity: Detecting Positive and Negative Tests (FSE 2024)Test Polarity: Detecting Positive and Negative Tests (FSE 2024)
Test Polarity: Detecting Positive and Negative Tests (FSE 2024)
 
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdfAI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
AI - Your Startup Sidekick (Leveraging AI to Bootstrap a Lean Startup).pdf
 
BDRSuite - #1 Cost effective Data Backup and Recovery Solution
BDRSuite - #1 Cost effective Data Backup and Recovery SolutionBDRSuite - #1 Cost effective Data Backup and Recovery Solution
BDRSuite - #1 Cost effective Data Backup and Recovery Solution
 
AI-driven Automation_ Transforming DevOps Practices.docx
AI-driven Automation_ Transforming DevOps Practices.docxAI-driven Automation_ Transforming DevOps Practices.docx
AI-driven Automation_ Transforming DevOps Practices.docx
 
How to Secure Your Kubernetes Software Supply Chain at Scale
How to Secure Your Kubernetes Software Supply Chain at ScaleHow to Secure Your Kubernetes Software Supply Chain at Scale
How to Secure Your Kubernetes Software Supply Chain at Scale
 
Generative AI The Key to Smarter, Faster IT Development.pdf
Generative AI The Key to Smarter, Faster IT Development.pdfGenerative AI The Key to Smarter, Faster IT Development.pdf
Generative AI The Key to Smarter, Faster IT Development.pdf
 
05. Ruby Control Structures - Ruby Core Teaching
05. Ruby Control Structures - Ruby Core Teaching05. Ruby Control Structures - Ruby Core Teaching
05. Ruby Control Structures - Ruby Core Teaching
 
Waze vs. Google Maps vs. Apple Maps, Who Else.pdf
Waze vs. Google Maps vs. Apple Maps, Who Else.pdfWaze vs. Google Maps vs. Apple Maps, Who Else.pdf
Waze vs. Google Maps vs. Apple Maps, Who Else.pdf
 
Applitools Autonomous 2.0 Sneak Peek.pdf
Applitools Autonomous 2.0 Sneak Peek.pdfApplitools Autonomous 2.0 Sneak Peek.pdf
Applitools Autonomous 2.0 Sneak Peek.pdf
 
Three available editions of Windows Servers crucial to your organization’s op...
Three available editions of Windows Servers crucial to your organization’s op...Three available editions of Windows Servers crucial to your organization’s op...
Three available editions of Windows Servers crucial to your organization’s op...
 
New York University degree Cert offer diploma Transcripta
New York University degree Cert offer diploma Transcripta New York University degree Cert offer diploma Transcripta
New York University degree Cert offer diploma Transcripta
 
Empowering Businesses with Intelligent Software Solutions - Grawlix
Empowering Businesses with Intelligent Software Solutions - GrawlixEmpowering Businesses with Intelligent Software Solutions - Grawlix
Empowering Businesses with Intelligent Software Solutions - Grawlix
 
pgroll - Zero-downtime, reversible, schema migrations for Postgres
pgroll - Zero-downtime, reversible, schema migrations for Postgrespgroll - Zero-downtime, reversible, schema migrations for Postgres
pgroll - Zero-downtime, reversible, schema migrations for Postgres
 
Unlocking the Future of Artificial Intelligence
Unlocking the Future of Artificial IntelligenceUnlocking the Future of Artificial Intelligence
Unlocking the Future of Artificial Intelligence
 
Unlocking value with event-driven architecture by Confluent
Unlocking value with event-driven architecture by ConfluentUnlocking value with event-driven architecture by Confluent
Unlocking value with event-driven architecture by Confluent
 
Mlm software - Binary, Board, Matrix, Monoline, Unilevel MLM Ecommerce or E-p...
Mlm software - Binary, Board, Matrix, Monoline, Unilevel MLM Ecommerce or E-p...Mlm software - Binary, Board, Matrix, Monoline, Unilevel MLM Ecommerce or E-p...
Mlm software - Binary, Board, Matrix, Monoline, Unilevel MLM Ecommerce or E-p...
 
vSAN_Tutorial_Presentation with important topics
vSAN_Tutorial_Presentation with important  topicsvSAN_Tutorial_Presentation with important  topics
vSAN_Tutorial_Presentation with important topics
 
Bring Strategic Portfolio Management to Monday.com using OnePlan - Webinar 18...
Bring Strategic Portfolio Management to Monday.com using OnePlan - Webinar 18...Bring Strategic Portfolio Management to Monday.com using OnePlan - Webinar 18...
Bring Strategic Portfolio Management to Monday.com using OnePlan - Webinar 18...
 

Introduction to Swift

  • 1. IOS BOOTCAMP 7° EDITION #pragma mark @ WCAP Catania 06/06/2015, v 1.2-S
  • 3. #PRAGMA MARK Started by a group of friends in 2012 Aim: create a community of iOS developers Non-profit org since Sept. 2013
  • 4. #PRAGMA MARK In 3 years: Organized a dozen events in northern Italy all over Italy! ! Created an active on-line community: fb.com/groups/pragmamark 2 editions of the #Pragma Conference
  • 5. #PRAGMA MARK Next edition: Florence, 9-10 Oct 2015 www.pragmaconference.com
  • 6. JUST FOR TODAY'S ATTENDEES 15% DISCOUNT CODE: ! PragmaLovesCatania " (limited to 30 tickets, so be quick!)
  • 8. HELLO WORLD ▸ Matteo Battaglio ▸ iOS dev @ Codermine ▸ #pragma mark co-founder
  • 12. LANGUAGE BIRTH I started work on the Swift Programming Language in July of 2010. I implemented much of the basic language structure, with only a few people knowing of its existence. A few other (amazing) people started contributing in earnest late in 2011, and it became a major focus for the Apple Developer Tools group in July 2013. — Chris Lattner
  • 13. LANGUAGE INSPIRATION The Swift Programming Language greatly benefited from the experiences hard-won by many other languages in the field, drawing ideas from Objective-C, Rust, Haskell, Ruby, Python, C#, CLU, and far too many others to list. — Chris Lattner
  • 15. SWIFT PROGRAMMING LANGUAGE imperative, functional, object oriented, multi-paradigm, static, strong typed, type safe, inferred, general purpose, compiled, fast, modern, elegant, clean, funny, happy, ❤
  • 17. Immutable & Mutable Functions & Closures Tuples & Pattern Matching Data Types & Instances Protocols & Extensions Generics & Optionals
  • 19. CONSTANTS & VARIABLES TYPE ANNOTATIONS & TYPE INFERENCE let constant: Int = 1 // Type Annotations let constant = 1 // Type Inference (as Int) let constant = 1 // readonly, cannot be re-assigned constant = 2 // ❌ ERROR !!! var variable = 1 // readwrite, can be re-assigned variable = 2 // OK By convention you should prefer to use 'let' over 'var'
  • 20. CONSTANTS & VARIABLES UNICODE CHARACTERS IN CONSTANT & VARIABLE NAMES let !!!! = 4 var """"" = 5 ! KILLER APPLICATION "
  • 21. VALUE & REFERENCE TYPES ENUMERATIONS & STRUCTURES VS CLASSES ▸ Enumerations & Structures are passed by Value ▸ Classes are passed by Reference ENUMERATIONS & STRUCTURES ARE ALWAYS COPIED WHEN THEY ARE PASSED AROUND IN THE CODE, AND DO NOT USE REFERENCE COUNTING.
  • 22. STRUCTURES MANY SWIFT LIBRARY'S BASE TYPES ARE STRUCTURES // String let string = "Swift" // Character let character: Character = "c" // Array let array = ["A", "B"] // Dictionary let dictionary = ["First" : 1, "Second" : 2]
  • 23. STRUCTURES CONSTANT & VARIABLE ARRAYS let constantArray = ["A"] var variableArray = ["A"] constantArray = ["X"] // ❌ ERROR !!! constantArray[0] = "Y" // ❌ ERROR !!! constantArray.append("B"); // ❌ ERROR !!! constantArray.removeAtIndex(0) // ❌ ERROR !!! variableArray = ["X"] // ["X"] variableArray[0] = "A" // ["A"] variableArray.append("B"); // ["A", "B"] variableArray.removeAtIndex(0) // ["B"]
  • 25. FUNCTIONS FIRST-CLASS FUNCTION ▸ assign a function to variable ▸ pass function as argument to another function ▸ return a function from a function ▸ functional programming patterns: map, filter, ...
  • 26. FUNCTIONS DECLARATION & CALL // declaration func foo(parameter1: Type1, parameter1: Type2) -> ReturnType { /* function body */ } // call foo(argument1, argument2) // external and local parameter names func bar(externalParameterName localParameterName: Type) { /* body use localParameterName */ } // call must use externalParameterName label bar(externalParameterName: argument)
  • 27. CLOSURES MEANING & SYNTAX // Closures are blocks of functionality that can be passed around { (parameter1: Type1, parameter2: Type2) -> ReturnType in / * ... */ } // Closures can capture and store references to any constants and // variables from the context in which they are defined.
  • 28. FUNCTIONS VS CLOSURES ▸ Global functions: NAMED CLOSURES / DO NOT CAPTURE ANY VALUES ▸ Nested functions: NAMED CLOSURES / CAPTURE VALUES FROM ENCLOSING FUNCTION ▸ Closure expressions: UNNAMED CLOSURES / CAPTURE VALUES FROM THEIR CONTEXT
  • 29. FUNCTIONS VS CLOSURES SORTING WITHOUT CLOSURES // define a function which takes an array and a sorting algorithm func sorted(array: [Int], algorithm: (Int, Int) -> Bool) -> [Int] { /* apply the sorting algorithm to the array */ } // define an array let array = [1, 2, 3] // define a sorting algorithm funtion func backwards(i1: Int, i2: Int) { return i1 > i2 } // call sorted var reversed = sorted(array, backwards)
  • 30. FUNCTIONS VS CLOSURES SORTING WITH CLOSURES 1/2 // Fully declared closure reversed = sorted(array, { (i1: Int, i2: Int) -> Bool in return i1 > i2 } ) // Infer closure type reversed = sorted(array, { (i1, i2) in return i1 > i2 } ) // Implicit returns reversed = sorted(array, { (i1, i2) in i1 > i2 } )
  • 31. FUNCTIONS VS CLOSURES SORTING WITH CLOSURES 2/2 // Shorthand argument names reversed = sorted(array, { $0 > $1 } ) // Trailing closure: outside of () only if it's function’s final argument reversed = sorted(array) { $0 > $1 } // Operator functions reversed = sorted(array, >)
  • 32. TUPLES & PATTERN MATCHING
  • 33. TUPLES LIGHTWEIGHT CONTAINERS FOR MULTIPLE VALUES let complex = (1.0, -2.0) // Compound Type: (Double, Double) let (real, imag) = complex // Decompose let (real, _) = complex // Underscores ignore value // Access by index let real = complex.0 let imag = complex.1 // Name elements let complex = (real: 1.0, imag: -2.0) let real = complex.real
  • 34. PATTERN MATCHING let point = (42, 42) switch point { // break by default case (0, 0): println("match a specific tuple") case (_, 0): println("ignore undescore value") case (let x, 1): println("bind a value to x") case let (x, y) where x == y: println("bind values which satify the where clause") default: println("must be exhaustive") }
  • 35. DATA TYPES & INSTANCES
  • 36. ENUMERATIONS, STRUCTURES & CLASSES COMMON CAPABILITIES ▸ Stored & Computed Properties ▸ Methods, Subscripts & Initializers ▸ Protocols & Extensions ▸ Access Control
  • 37. ENUMERATIONS, STRUCTURES & CLASSES public class Vehicle { // stored instance property private let name: String // computed instance property public var formattedName: String { return "vehicle: (name)" } // type property class var maxSpeed : Int { return 299_792_458 } // initializer init (name: String) { self.name = name } // instance method internal func move() { /* ... */ } }
  • 38. CLASSES Only ADDITIONAL CAPABILITIES: ▸ Inheritance ▸ Type casting ▸ Deinitializers ▸ Reference counting
  • 39. CLASSES Only public class Car: Vehicle { // inheritance // override public override var formattedName: String { return "car: (name)" } // designated initializer override init(name: String) { super.init(name: name);} // convenience initializer convenience init() { self.init(name: "Car") } // deinitializer deinit { /* clean up */ } } let vehicle = Car(name: "Supercar") let car = vehicle as Car // Type Casting
  • 41. PROTOCOLS // Available for Enumerations, Structures & Classes protocol SomeProtocol { // define a set of requirements var instanceProperty: Type { get set } // require instance properties class var typeProperty: Type { get set } // require type properties func someMethod() // require instance methods class func someTypeMethod() // require type methods init() // require initializers }
  • 42. EXTENSIONS // Available for Enumerations, Structures & Classes extension SomeType: SomeProtocol { // add protocol conformance var stored = 1 // ❌ ERROR !!! // CANNOT add store properties ! var computed: String { /* ... */ } // add computed properties func method() { /* ... */ } // add methods subscript(i: Int) -> String { /* ... */ } // add subscripts init(parameter: Type) { /* ... */ } // add initializers enum SomeEnum { /* ... */ } // add nested types }
  • 43. EXTENSIONS EXTENSIONS CAN EXTEND ALSO SWIFT LIBRARY TYPES extension Int { func times(task: () -> ()) { for i in 0 ..< self { task() } } } 3.times({ println("Developer! ") }) // Developer! Developer! Developer! !
  • 45. GENERICS // Specific Functions func swapTwoStrings(inout a: String, inout b: String) { let temporaryA = a; a = b; b = temporaryA } func swapTwoDoubles(inout a: Double, inout b: Double) { let temporaryA = a; a = b; b = temporaryA } // Generic Function func swapTwoValues<T>(inout a: T, inout b: T) { let temporaryA = a; a = b; b = temporaryA } var someInt = 1, anotherInt = 2 swapTwoValues(&someInt, &anotherInt) // T == Int // someInt == 2, anotherInt == 1
  • 46. GENERICS WHERE CLAUSES ON TYPE CONSTRAINTS protocol Container { typealias ItemType /* ... */ } func allItemsMatch< C1: Container, C2: Container where C1.ItemType == C2.ItemType, C1.ItemType: Equatable> (container1: C1, container2: C2) -> Bool { if container1.count != container2.count { return false } for i in 0..<container1.count { if container1[i] != container2[i] { return false } } return true // all items match } }
  • 47. 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
  • 48. OPTIONALS // Force unwrap let optionalInt: Int? = 42 let definitelyInt = optionalInt! // throws runtime error if nil // Optional binding if let definitelyInt = optionalInt { // runs if optionalInt is not nil and sets definitelyInt: Int } // Implicitly Unwrapped Optionals var assumedInt: Int! // set to nil assumedInt = 42 var implicitInt: Int = assumedInt // do not need an exclamation mark assumedInt = nil implicitInt = assumedInt // ❌ RUNTIME ERROR !!!
  • 49. OPTIONALS class Car { var model: String init(model: String) { self.model = model } func jump() -> String? { if model == "Supercar" { return "!⚡" } else { return nil } } } // Return type of chaining is always optional var car1: Car? = nil; car1?.model // nil: String? var car2: Car? = Car(model: "Supercar"); car2?.model // "Supercar": String? // Chain on optional return value car1?.jump()?.hasPrefix("!") // type Bool?
  • 50. OPTIONALS A GENERIC ENUMERATION WITH ASSOCIATED VALUE enum Optional<T> : Reflectable, NilLiteralConvertible { case None case Some(T) /* ... */ } var maybeInt1: Int? = nil var maybeInt2: Optional<Int> = .None maybeInt1 = 42 maybeInt2 = .Some(42)
  • 52. SWIFT VS ... ? ▸ Swift vs Scala ▸ Swift vs Rust ▸ Swift vs C# Swift is Objective-C without the C
  • 53. OPEN SOURCE SWIFT ? Guys, feel free to make up your own dragons if you want, but your speculation is just that: speculation. We literally have not even discussed this yet, because we have a ton of work to do [...] You can imagine that many of us want it to be open source and part of llvm, but the discussion hasn't happened yet, and won't for some time. — Chris Lattner @ llvmdev
  • 54. WHAT SWIFT IS MISSING? [ SWIFT 1.2 IN XCODE 6.3 ] ▸ Compiler attributes and Preprocessor ▸ Exceptions, KVO, KVC and proper Reflection HTTPS://GITHUB.COM/KSM/SWIFTINFLUX
  • 55. SWIFT IN PRODUCTION? ▸ Companies are doing it ▸ Freelances are doing it ▸ Many of us are doing it ▸ But be careful if you do it! A few apps that were built using Swift @ apple.com
  • 56. WWDC next week (8-12 June) Great expectations for Swift...
  • 57. THANKSYou can find me on the Internet! twitter ! @m4dbat github ! madbat " matteo.battaglio@pragmamark.org