SlideShare una empresa de Scribd logo
1 de 86
Server Side Swift
Chad Moone
WP Dev Day 2017
• A new programming language (2014)
• Developed by Chris Lattner & Apple
• Compiled, based on LLVM stack
• Static, strong, and inferred typing
• Multi-paradigm (OO, functional, imperative, protocol-oriented)
• Focused on speed & safety
Swift
What even is it?
• A Joy to Work In
• Expressive, yet concise
• Safety Front-and-Center
• Incredibly Intelligent Compiler
• Robust Type System
• Rapidly growing in popularity
Why Swift?
Here’s why we love it
Swift Evolution
• Hello World!
• Core language features
• Apple platform support
Initial Release
1.0 (2014)
Swift Evolution
• Hello World!
• Core language features
• Apple platform support
Initial Release Open Source
1.0 (2014) 2.0 (2015)
• OSS compiler & standard
library
• Linux support
• Error handling
• Protocol extensions
Swift Evolution
• Hello World!
• Core language features
• Apple platform support
Initial Release Open Source Community-Driven
Refinement
1.0 (2014) 2.0 (2015) 3.0 (2016)
• OSS compiler & standard
library
• Linux support
• Error handling
• Protocol extensions
• All changes via community
evolution process
• Major syntax changes for
coherence & consistency
• Std Lib rewrite
• Official API design
guidelines
Swift Evolution
• Hello World!
• Core language features
• Apple platform support
Initial Release Open Source Community-Driven
Refinement Stability & Polish
1.0 (2014) 2.0 (2015) 3.0 (2016) 4.0 (2017)
• OSS compiler & standard
library
• Linux support
• Error handling
• Protocol extensions
• All changes via community
evolution process
• Major syntax changes for
coherence & consistency
• Std Lib rewrite
• Official API design
guidelines
• Strings enhancements
• Automatic archival &
serialization
• Reached top 10 in both
TIOBE & IEEE language
indexes
• Server APIs Working
Group
Swift on the Server
Swift Server-Side Frameworks
The Major Players
10k ⭐️
Community-Driven
Version 2.1
Vapor
12k ⭐️
Driven by community &
PerfectlySoft
Version 2.0
Perfect
6k ⭐️
Driven by IBM & community
Version 1.7
Kitura
• github.com/rymcol/Linux-Server-Side-Swift-Benchmarking
• Used an identical simple blog application
• Both HTML & bare-bones JSON versions
• Express.js was used for the Node comparison
Server Performance Shootout
0
3000
6000
9000
12000
Perfect Kitura Vapor Node
11K 11K
9K
7K
Requests/Second
Server Performance Shootout
• HTML Requests/Second
https://github.com/rymcol/Linux-Server-Side-Swift-Benchmarking
0
0.7
1.4
2.1
2.8
Perfect Kitura Vapor Node
2
2
1
3
Average Latency (ms)
Server Performance Shootout
• HTML Requests/Second
• HTML Average Latency
https://github.com/rymcol/Linux-Server-Side-Swift-Benchmarking
0
5000
10000
15000
20000
Perfect Kitura Vapor Node
20K
11K
14K
9K
Requests/Second
Server Performance Shootout
• HTML Requests/Second
• HTML Average Latency
• JSON API Requests/Second
https://github.com/rymcol/Linux-Server-Side-Swift-Benchmarking
0
0.6
1.2
1.8
2.4
Perfect Kitura Vapor Node
1.0
1.9
0.8
2.2
Average Latency (ms)
Server Performance Shootout
• HTML Requests/Second
• HTML Average Latency
• JSON API Requests/Second
• JSON API Average Latency
https://github.com/rymcol/Linux-Server-Side-Swift-Benchmarking
0
4
8
12
16
Perfect Kitura Vapor Node
1.30 1.40 1.40
15.30
Memory Footprint (MB)
Server Performance Shootout
• HTML Requests/Second
• HTML Average Latency
• JSON API Requests/Second
• JSON API Average Latency
• Memory Footprint (Startup)
https://github.com/rymcol/Linux-Server-Side-Swift-Benchmarking
0
75
150
225
300
Perfect Kitura Vapor Node
3
174
246
61
Memory Footprint (MB)
Server Performance Shootout
• HTML Requests/Second
• HTML Average Latency
• JSON API Requests/Second
• JSON API Average Latency
• Memory Footprint (Startup)
• Memory Footprint (High Load)
https://github.com/rymcol/Linux-Server-Side-Swift-Benchmarking
Swift’s Greatest Hits
vol 1
1
Named Arguments
Clarity at the point of use
func logMessage(message:String,
prefix: String,
suffix: String) {
print("(prefix)-(message)-(suffix)")
}
Named Arguments
Clarity at the point of use
SWIFT’S GREATEST HITS
func logMessage(message:String,
prefix: String,
suffix: String) {
print("(prefix)-(message)-(suffix)")
}
logMessage("Beautiful",
"Hello",
“World”)
Named Arguments
SWIFT’S GREATEST HITS
Clarity at the point of use
func logMessage(message:String,
prefix: String,
suffix: String) {
print("(prefix)-(message)-(suffix)")
}
logMessage(message: “Beautiful”,
prefix: "Hello",
suffix: “World”)
Named Arguments
SWIFT’S GREATEST HITS
Clarity at the point of use
func logMessage(_ message:String,
withPrefix prefix: String,
andSuffix suffix: String) {
print("(prefix)-(message)-(suffix)")
}
logMessage("Beautiful",
withPrefix: "Hello",
andSuffix: “World")
Named Arguments
SWIFT’S GREATEST HITS
Clarity at the point of use
2
Type Inference
Only what’s needed
let meaningOfLife: Int = 42
let pi: Double = 3.14159
let anotherPi: Double = 3 + 0.14159
let apple: Apple = Apple()
let appleDescription: String = apple.toString()
Type Inference
Only what’s needed
SWIFT’S GREATEST HITS
let meaningOfLife = 42
let pi = 3.14159
let anotherPi = 3 + 0.14159
let apple = Apple()
let appleDescription = apple.toString()
Type Inference
Only what’s needed
SWIFT’S GREATEST HITS
let currentPoints: UInt = 42
let miniPi: Float = 3.14159
var color: UIColor
if pi > 4 {
color = .green
} else {
color = .red
}
Type Inference
Only what’s needed
SWIFT’S GREATEST HITS
3
Extensions & Protocols
Redefining Definition TM
extension String {
func exclaimed() -> String {
return "(self)!"
}
}
let greeting = "Hello".exclaimed() // "Hello!"
Extensions & Protocols
Redefining Definition
SWIFT’S GREATEST HITS
protocol FullyNamed {
var fullName: String {get}
}
Extensions & Protocols
Redefining Definition
SWIFT’S GREATEST HITS
protocol FullyNamed {
var fullName: String {get}
}
protocol Introducing: FullyNamed {
func introduce() -> String
}
Extensions & Protocols
Redefining Definition
SWIFT’S GREATEST HITS
protocol FullyNamed {
var fullName: String {get}
}
protocol Introducing: FullyNamed {
func introduce() -> String
}
extension Introducing {
func introduce() -> String { return : "Hi, I’m (fullName)!” }
}
Extensions & Protocols
Redefining Definition
SWIFT’S GREATEST HITS
protocol FullyNamed {
var fullName: String {get}
}
protocol Introducing: FullyNamed {
func introduce() -> String
}
extension Introducing {
func introduce() -> String { return : "Hi, I’m (fullName)!” }
}
struct Person: Introducing {
var fullName: String { return "(firstName) (lastName)" }
}
let p = Person(firstName: "Chad", lastName: "Moone")
p.introduce() // "Hi, I'm Chad Moone!"
Extensions & Protocols
Redefining Definition
SWIFT’S GREATEST HITS
4
Optionality
Make nil Great Again
Optionality
var myObject: Object = nil
Make nil Great Again
SWIFT’S GREATEST HITS
Optionality
var myObject: Object = nil
myObject.toString()
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject: Object = nil
myObject.toString() // <—- 💣💥💀
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
Optionality
var myObject: Object = nil
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject: Object = nil // <—- 🚨👾🚨*
*👾 == “compiler”
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject: Object = Object()
var optionalObject: Object? = nil
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject = Object()
var optionalObject: Object?
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject = Object()
var optionalObject: Object?
myObject = nil
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject = Object()
var optionalObject: Object?
myObject = nil // <—- 🚨👾🚨
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject = Object()
var optionalObject: Object?
myObject = otherObject // <—- ✅👾✅
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject = Object()
var optionalObject: Object?
myObject = otherObject
optionalObject = Object()
optionalObject = nil
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject = Object()
var optionalObject: Object?
myObject = otherObject
optionalObject = Object()
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject = Object()
var optionalObject: Object?
myObject = otherObject
optionalObject = Object()
myObject.print()
optionalObject.print()
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject = Object()
var optionalObject: Object?
myObject = otherObject
optionalObject = Object()
myObject.print() // <—- guaranteed to be ✅
optionalObject.print()
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject = Object()
var optionalObject: Object?
myObject = otherObject
optionalObject = Object()
myObject.print() // <—- guaranteed to be ✅
optionalObject.print() // <—- 🚨👾🚨
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject = Object()
var optionalObject: Object?
myObject = otherObject
optionalObject = Object()
myObject.print() // <—- guaranteed to be ✅
optionalObject?.print()
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject = Object()
var optionalObject: Object?
myObject = otherObject
optionalObject = Object()
myObject.print() // <—- guaranteed to be ✅
optionalObject?.print() // <—- has value, so ✅
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
var myObject = Object()
var optionalObject: Object?
myObject = otherObject
optionalObject = Object()
myObject.print() // <—- guaranteed to be ✅
optionalObject?.print() // <—- has value, so ✅
optionalObject = nil
optionalObject?.print() // <—- no value == no op
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
func setAlarm(time: Date, message: String?) {
alarmTime = time
if let message = message {
message.uppercased()
addExclamations(message)
emojify(message)
alarmMessage = message
}
}
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
func setAlarm(time: Date, message: String?) {
alarmTime = time
guard let message = message else {
return
}
message.uppercased()
addExclamations(message)
emojify(message)
alarmMessage = message
}
Optionality
Make nil Great Again
SWIFT’S GREATEST HITS
5
Enums & Generics
Safe, yet flexible
Enums & Generics
enum CompassPoint {
case north
case south
case east
case west
}
var directionToHead = CompassPoint.west
var directionToShore: CompassPoint = .east
Safe, yet flexible
SWIFT’S GREATEST HITS
Enums & Generics
switch directionToTravel {
case .north:
print("To Canada!")
case .south:
print("To Mexico!")
}
Safe, yet flexible
SWIFT’S GREATEST HITS
Enums & Generics
switch directionToTravel {
case .north:
print("To Canada!")
case .south:
print("To Mexico!")
} // <—- 🚨👾🚨 Must be exhaustive!!
Safe, yet flexible
SWIFT’S GREATEST HITS
Enums & Generics
switch directionToTravel {
case .north:
print("To Canada!")
case .south:
print("To Mexico!")
default:
print("Into the ocean!")
}
Safe, yet flexible
SWIFT’S GREATEST HITS
Enums & Generics
enum Planet: Int {
case mercury = 1
case venus = 2
case earth = 3
case mars = 4
case jupiter = 5
case saturn = 6
case uranus = 7
case neptune = 8
}
Safe, yet flexible
SWIFT’S GREATEST HITS
Enums & Generics
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter,
saturn, uranus, neptune
}
Safe, yet flexible
SWIFT’S GREATEST HITS
Enums & Generics
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter,
saturn, uranus, neptune
}
if let somePlanet = Planet(rawValue: 11) {
switch somePlanet {
case .earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
} else {
print("There isn't a planet at position (positionToFind)")
} // Prints "There isn't a planet at position 11"
Safe, yet flexible
SWIFT’S GREATEST HITS
Enums & Generics
enum Either {
case str(String)
case num(Double)
}
var a = Either.str("hello")
a = .num(1.0)
Safe, yet flexible
SWIFT’S GREATEST HITS
Enums & Generics
enum Trade {
case Buy(stock: String, amount: Int)
case Sell(stock: String, amount: Int)
}
Safe, yet flexible
SWIFT’S GREATEST HITS
Enums & Generics
enum Trade {
case Buy(stock: String, amount: Int)
case Sell(stock: String, amount: Int)
}
func executeTrade(_ trade: Trade) { /* magic */ }
Safe, yet flexible
SWIFT’S GREATEST HITS
Enums & Generics
enum Trade {
case Buy(stock: String, amount: Int)
case Sell(stock: String, amount: Int)
}
func executeTrade(_ trade: Trade) { /* magic */ }
let purchase = Trade.Buy(stock: "AAPL", amount: 20)
executeTrade(purchase)
let sale = Trade.Sell(stock: "SNAP", amount: 500)
executeTrade(sale)
Safe, yet flexible
SWIFT’S GREATEST HITS
Enums & Generics
enum Either {
case str(String)
case num(Double)
}
var a = Either.str("hello")
a = .num(1.0)
Safe, yet flexible
SWIFT’S GREATEST HITS
Enums & Generics
enum Optional<Wrapped> {
case some(Wrapped)
case none
}
var possibleInteger: Optional<Int> = .none
possibleInteger = .some(100)
Safe, yet flexible
SWIFT’S GREATEST HITS
6
Automatic Reference Counting
The “other” ARC
Automatic Reference Counting
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("Bye, (name)!") }
}
var p1: Person? = Person(name: "Chad")
p1 = nil // "Bye, Chad”
p1 = Person(name: "Murray")
var p2 = p1
p1 = nil // Murray still has an active reference
p2 = Person(name: "Bruce") // "Bye, Murray"
The “other” ARC
SWIFT’S GREATEST HITS
Automatic Reference Counting
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("Bye, (name)!") }
}
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
var tenant: Person?
deinit { print("Apartment (unit) is being deinitialized") }
}
The “other” ARC
SWIFT’S GREATEST HITS
Automatic Reference Counting
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("Bye, (name)!") }
}
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
var tenant: Person?
deinit { print("Apartment (unit) is being deinitialized") }
}
var p: Person? = Person(name: "Chad")
var a: Apartment? = Apartment(unit: "5C")
p?.apartment = a
a?.tenant = p
p = nil // a still has a reference
a = nil // p still has a reference
The “other” ARC
SWIFT’S GREATEST HITS
Automatic Reference Counting
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("Bye, (name)!") }
}
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
weak var tenant: Person?
deinit { print("Apartment (unit) is being deinitialized") }
}
var p: Person? = Person(name: "Chad")
var a: Apartment? = Apartment(unit: "5C")
p?.apartment = a
a?.tenant = p
The “other” ARC
SWIFT’S GREATEST HITS
Automatic Reference Counting
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("Bye, (name)!") }
}
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
weak var tenant: Person?
deinit { print("Apartment (unit) is being deinitialized") }
}
var p: Person? = Person(name: "Chad")
var a: Apartment? = Apartment(unit: "5C")
p?.apartment = a
a?.tenant = p
p = nil // "Bye, Chad!"
a = nil // "Apartment 5C is being deinitialized"
The “other” ARC
SWIFT’S GREATEST HITS
Swift’s Greatest Hits
vol 1
Swift Playgrounds
• For macOS & iPad
• Start playing with the full power of
swift in seconds
• Tons of tutorials and other
resources
• REPL on Steroids
macOS Playgrounds Demo
iPad Playgrounds
iPad Playgrounds
Swift Playgrounds
• For macOS & iPad
• Start playing with the full power of
swift in seconds
• Tons of tutorials and other
resources
• REPL on Steroids
• swift.org
• developer.apple.com/swift
• github.com/apple/swift
• Free Swift programming book series (regularly updated)
Getting Started
Questions?

Más contenido relacionado

La actualidad más candente

Akka Http , Routes, Streams with Scala
Akka Http , Routes, Streams with ScalaAkka Http , Routes, Streams with Scala
Akka Http , Routes, Streams with ScalaJerry Kuru
 
Deploying Plack Web Applications: OSCON 2011
Deploying Plack Web Applications: OSCON 2011Deploying Plack Web Applications: OSCON 2011
Deploying Plack Web Applications: OSCON 2011Tatsuhiko Miyagawa
 
Integration using Apache Camel and Groovy
Integration using Apache Camel and GroovyIntegration using Apache Camel and Groovy
Integration using Apache Camel and GroovyClaus Ibsen
 
Apache Camel - The integration library
Apache Camel - The integration libraryApache Camel - The integration library
Apache Camel - The integration libraryClaus Ibsen
 
Построение распределенной системы сбора данных с помощью RabbitMQ, Alvaro Vid...
Построение распределенной системы сбора данных с помощью RabbitMQ, Alvaro Vid...Построение распределенной системы сбора данных с помощью RabbitMQ, Alvaro Vid...
Построение распределенной системы сбора данных с помощью RabbitMQ, Alvaro Vid...Ontico
 
Automating Your Workflow with Gulp.js - php[world] 2016
Automating Your Workflow with Gulp.js - php[world] 2016Automating Your Workflow with Gulp.js - php[world] 2016
Automating Your Workflow with Gulp.js - php[world] 2016Colin O'Dell
 
Building real time applications with Symfony2
Building real time applications with Symfony2Building real time applications with Symfony2
Building real time applications with Symfony2Antonio Peric-Mazar
 
Dissecting the rabbit: RabbitMQ Internal Architecture
Dissecting the rabbit: RabbitMQ Internal ArchitectureDissecting the rabbit: RabbitMQ Internal Architecture
Dissecting the rabbit: RabbitMQ Internal ArchitectureAlvaro Videla
 
Exploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices💡 Tomasz Kogut
 
Fluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshellFluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshellN Masahiro
 
Kubernetes Internals
Kubernetes InternalsKubernetes Internals
Kubernetes InternalsShimi Bandiel
 
Titanium 3.2 CLI - TiAppCamp2 - 11/2/2013
Titanium 3.2 CLI - TiAppCamp2 - 11/2/2013Titanium 3.2 CLI - TiAppCamp2 - 11/2/2013
Titanium 3.2 CLI - TiAppCamp2 - 11/2/2013Chris Barber
 
Java & low latency applications
Java & low latency applicationsJava & low latency applications
Java & low latency applicationsRuslan Shevchenko
 
Exploring the Titanium CLI - Codestrong 2012
Exploring the Titanium CLI - Codestrong 2012Exploring the Titanium CLI - Codestrong 2012
Exploring the Titanium CLI - Codestrong 2012Chris Barber
 
Scalalable Language for a Scalable Web
Scalalable Language for a Scalable WebScalalable Language for a Scalable Web
Scalalable Language for a Scalable WebTimothy Perrett
 
Killer Docker Workflows for Development
Killer Docker Workflows for DevelopmentKiller Docker Workflows for Development
Killer Docker Workflows for DevelopmentChris Tankersley
 

La actualidad más candente (20)

Akka Http , Routes, Streams with Scala
Akka Http , Routes, Streams with ScalaAkka Http , Routes, Streams with Scala
Akka Http , Routes, Streams with Scala
 
Deploying Plack Web Applications: OSCON 2011
Deploying Plack Web Applications: OSCON 2011Deploying Plack Web Applications: OSCON 2011
Deploying Plack Web Applications: OSCON 2011
 
Integration using Apache Camel and Groovy
Integration using Apache Camel and GroovyIntegration using Apache Camel and Groovy
Integration using Apache Camel and Groovy
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
 
Plack at YAPC::NA 2010
Plack at YAPC::NA 2010Plack at YAPC::NA 2010
Plack at YAPC::NA 2010
 
Apache Camel - The integration library
Apache Camel - The integration libraryApache Camel - The integration library
Apache Camel - The integration library
 
Построение распределенной системы сбора данных с помощью RabbitMQ, Alvaro Vid...
Построение распределенной системы сбора данных с помощью RabbitMQ, Alvaro Vid...Построение распределенной системы сбора данных с помощью RabbitMQ, Alvaro Vid...
Построение распределенной системы сбора данных с помощью RabbitMQ, Alvaro Vid...
 
Automating Your Workflow with Gulp.js - php[world] 2016
Automating Your Workflow with Gulp.js - php[world] 2016Automating Your Workflow with Gulp.js - php[world] 2016
Automating Your Workflow with Gulp.js - php[world] 2016
 
Building real time applications with Symfony2
Building real time applications with Symfony2Building real time applications with Symfony2
Building real time applications with Symfony2
 
Dissecting the rabbit: RabbitMQ Internal Architecture
Dissecting the rabbit: RabbitMQ Internal ArchitectureDissecting the rabbit: RabbitMQ Internal Architecture
Dissecting the rabbit: RabbitMQ Internal Architecture
 
Exploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservicesExploring Twitter's Finagle technology stack for microservices
Exploring Twitter's Finagle technology stack for microservices
 
Fluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshellFluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshell
 
How DSL works on Ruby
How DSL works on RubyHow DSL works on Ruby
How DSL works on Ruby
 
Kubernetes Internals
Kubernetes InternalsKubernetes Internals
Kubernetes Internals
 
Titanium 3.2 CLI - TiAppCamp2 - 11/2/2013
Titanium 3.2 CLI - TiAppCamp2 - 11/2/2013Titanium 3.2 CLI - TiAppCamp2 - 11/2/2013
Titanium 3.2 CLI - TiAppCamp2 - 11/2/2013
 
Java & low latency applications
Java & low latency applicationsJava & low latency applications
Java & low latency applications
 
Exploring the Titanium CLI - Codestrong 2012
Exploring the Titanium CLI - Codestrong 2012Exploring the Titanium CLI - Codestrong 2012
Exploring the Titanium CLI - Codestrong 2012
 
Scalalable Language for a Scalable Web
Scalalable Language for a Scalable WebScalalable Language for a Scalable Web
Scalalable Language for a Scalable Web
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Killer Docker Workflows for Development
Killer Docker Workflows for DevelopmentKiller Docker Workflows for Development
Killer Docker Workflows for Development
 

Similar a Server Side Swift

IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileIVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileAmazon Web Services Japan
 
Flask With Server-Sent Event
Flask With Server-Sent EventFlask With Server-Sent Event
Flask With Server-Sent EventTencent
 
Using Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsUsing Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsSerge Stinckwich
 
Open Source Swift Under the Hood
Open Source Swift Under the HoodOpen Source Swift Under the Hood
Open Source Swift Under the HoodC4Media
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015fukamachi
 
Fast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCFast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCTim Burks
 
Go from a PHP Perspective
Go from a PHP PerspectiveGo from a PHP Perspective
Go from a PHP PerspectiveBarry Jones
 
Kubernetes Workshop
Kubernetes WorkshopKubernetes Workshop
Kubernetes Workshoploodse
 
Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020Andrea Scuderi
 
Java プログラマーのための Swift 入門 #中央線Meetup
Java プログラマーのための Swift 入門 #中央線MeetupJava プログラマーのための Swift 入門 #中央線Meetup
Java プログラマーのための Swift 入門 #中央線MeetupShinya Mochida
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineChun-Yu Wang
 
A Brief History of OWIN
A Brief History of OWINA Brief History of OWIN
A Brief History of OWINRyan Riley
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011tobiascrawley
 

Similar a Server Side Swift (20)

IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & MobileIVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
IVS CTO Night And Day 2018 Winter - [re:Cap] Serverless & Mobile
 
Flask With Server-Sent Event
Flask With Server-Sent EventFlask With Server-Sent Event
Flask With Server-Sent Event
 
Using Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systemsUsing Smalltalk for controlling robotics systems
Using Smalltalk for controlling robotics systems
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
Open Source Swift Under the Hood
Open Source Swift Under the HoodOpen Source Swift Under the Hood
Open Source Swift Under the Hood
 
Apache Thrift
Apache ThriftApache Thrift
Apache Thrift
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015Woo: Writing a fast web server @ ELS2015
Woo: Writing a fast web server @ ELS2015
 
Fast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCFast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPC
 
Go from a PHP Perspective
Go from a PHP PerspectiveGo from a PHP Perspective
Go from a PHP Perspective
 
About Clack
About ClackAbout Clack
About Clack
 
Kubernetes Workshop
Kubernetes WorkshopKubernetes Workshop
Kubernetes Workshop
 
Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020Aws Lambda in Swift - NSLondon - 3rd December 2020
Aws Lambda in Swift - NSLondon - 3rd December 2020
 
Edge architecture ieee international conference on cloud engineering
Edge architecture   ieee international conference on cloud engineeringEdge architecture   ieee international conference on cloud engineering
Edge architecture ieee international conference on cloud engineering
 
Java プログラマーのための Swift 入門 #中央線Meetup
Java プログラマーのための Swift 入門 #中央線MeetupJava プログラマーのための Swift 入門 #中央線Meetup
Java プログラマーのための Swift 入門 #中央線Meetup
 
How to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machineHow to implement a simple dalvik virtual machine
How to implement a simple dalvik virtual machine
 
A Brief History of OWIN
A Brief History of OWINA Brief History of OWIN
A Brief History of OWIN
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
Angular2
Angular2Angular2
Angular2
 
Next .NET and C#
Next .NET and C#Next .NET and C#
Next .NET and C#
 

Último

Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersMairaAshraf6
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxSCMS School of Architecture
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxNadaHaitham1
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxmaisarahman1
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityMorshed Ahmed Rahath
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Arindam Chakraborty, Ph.D., P.E. (CA, TX)
 
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEGEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEselvakumar948
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationBhangaleSonal
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdfKamal Acharya
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VDineshKumar4165
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiessarkmank1
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesRAJNEESHKUMAR341697
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Servicemeghakumariji156
 

Último (20)

Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptx
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEGEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 

Server Side Swift

  • 1. Server Side Swift Chad Moone WP Dev Day 2017
  • 2.
  • 3. • A new programming language (2014) • Developed by Chris Lattner & Apple • Compiled, based on LLVM stack • Static, strong, and inferred typing • Multi-paradigm (OO, functional, imperative, protocol-oriented) • Focused on speed & safety Swift What even is it?
  • 4. • A Joy to Work In • Expressive, yet concise • Safety Front-and-Center • Incredibly Intelligent Compiler • Robust Type System • Rapidly growing in popularity Why Swift? Here’s why we love it
  • 5. Swift Evolution • Hello World! • Core language features • Apple platform support Initial Release 1.0 (2014)
  • 6. Swift Evolution • Hello World! • Core language features • Apple platform support Initial Release Open Source 1.0 (2014) 2.0 (2015) • OSS compiler & standard library • Linux support • Error handling • Protocol extensions
  • 7. Swift Evolution • Hello World! • Core language features • Apple platform support Initial Release Open Source Community-Driven Refinement 1.0 (2014) 2.0 (2015) 3.0 (2016) • OSS compiler & standard library • Linux support • Error handling • Protocol extensions • All changes via community evolution process • Major syntax changes for coherence & consistency • Std Lib rewrite • Official API design guidelines
  • 8. Swift Evolution • Hello World! • Core language features • Apple platform support Initial Release Open Source Community-Driven Refinement Stability & Polish 1.0 (2014) 2.0 (2015) 3.0 (2016) 4.0 (2017) • OSS compiler & standard library • Linux support • Error handling • Protocol extensions • All changes via community evolution process • Major syntax changes for coherence & consistency • Std Lib rewrite • Official API design guidelines • Strings enhancements • Automatic archival & serialization • Reached top 10 in both TIOBE & IEEE language indexes • Server APIs Working Group
  • 9. Swift on the Server
  • 10. Swift Server-Side Frameworks The Major Players 10k ⭐️ Community-Driven Version 2.1 Vapor 12k ⭐️ Driven by community & PerfectlySoft Version 2.0 Perfect 6k ⭐️ Driven by IBM & community Version 1.7 Kitura
  • 11. • github.com/rymcol/Linux-Server-Side-Swift-Benchmarking • Used an identical simple blog application • Both HTML & bare-bones JSON versions • Express.js was used for the Node comparison Server Performance Shootout
  • 12. 0 3000 6000 9000 12000 Perfect Kitura Vapor Node 11K 11K 9K 7K Requests/Second Server Performance Shootout • HTML Requests/Second https://github.com/rymcol/Linux-Server-Side-Swift-Benchmarking
  • 13. 0 0.7 1.4 2.1 2.8 Perfect Kitura Vapor Node 2 2 1 3 Average Latency (ms) Server Performance Shootout • HTML Requests/Second • HTML Average Latency https://github.com/rymcol/Linux-Server-Side-Swift-Benchmarking
  • 14. 0 5000 10000 15000 20000 Perfect Kitura Vapor Node 20K 11K 14K 9K Requests/Second Server Performance Shootout • HTML Requests/Second • HTML Average Latency • JSON API Requests/Second https://github.com/rymcol/Linux-Server-Side-Swift-Benchmarking
  • 15. 0 0.6 1.2 1.8 2.4 Perfect Kitura Vapor Node 1.0 1.9 0.8 2.2 Average Latency (ms) Server Performance Shootout • HTML Requests/Second • HTML Average Latency • JSON API Requests/Second • JSON API Average Latency https://github.com/rymcol/Linux-Server-Side-Swift-Benchmarking
  • 16. 0 4 8 12 16 Perfect Kitura Vapor Node 1.30 1.40 1.40 15.30 Memory Footprint (MB) Server Performance Shootout • HTML Requests/Second • HTML Average Latency • JSON API Requests/Second • JSON API Average Latency • Memory Footprint (Startup) https://github.com/rymcol/Linux-Server-Side-Swift-Benchmarking
  • 17. 0 75 150 225 300 Perfect Kitura Vapor Node 3 174 246 61 Memory Footprint (MB) Server Performance Shootout • HTML Requests/Second • HTML Average Latency • JSON API Requests/Second • JSON API Average Latency • Memory Footprint (Startup) • Memory Footprint (High Load) https://github.com/rymcol/Linux-Server-Side-Swift-Benchmarking
  • 19. 1 Named Arguments Clarity at the point of use
  • 20. func logMessage(message:String, prefix: String, suffix: String) { print("(prefix)-(message)-(suffix)") } Named Arguments Clarity at the point of use SWIFT’S GREATEST HITS
  • 21. func logMessage(message:String, prefix: String, suffix: String) { print("(prefix)-(message)-(suffix)") } logMessage("Beautiful", "Hello", “World”) Named Arguments SWIFT’S GREATEST HITS Clarity at the point of use
  • 22. func logMessage(message:String, prefix: String, suffix: String) { print("(prefix)-(message)-(suffix)") } logMessage(message: “Beautiful”, prefix: "Hello", suffix: “World”) Named Arguments SWIFT’S GREATEST HITS Clarity at the point of use
  • 23. func logMessage(_ message:String, withPrefix prefix: String, andSuffix suffix: String) { print("(prefix)-(message)-(suffix)") } logMessage("Beautiful", withPrefix: "Hello", andSuffix: “World") Named Arguments SWIFT’S GREATEST HITS Clarity at the point of use
  • 25. let meaningOfLife: Int = 42 let pi: Double = 3.14159 let anotherPi: Double = 3 + 0.14159 let apple: Apple = Apple() let appleDescription: String = apple.toString() Type Inference Only what’s needed SWIFT’S GREATEST HITS
  • 26. let meaningOfLife = 42 let pi = 3.14159 let anotherPi = 3 + 0.14159 let apple = Apple() let appleDescription = apple.toString() Type Inference Only what’s needed SWIFT’S GREATEST HITS
  • 27. let currentPoints: UInt = 42 let miniPi: Float = 3.14159 var color: UIColor if pi > 4 { color = .green } else { color = .red } Type Inference Only what’s needed SWIFT’S GREATEST HITS
  • 29. extension String { func exclaimed() -> String { return "(self)!" } } let greeting = "Hello".exclaimed() // "Hello!" Extensions & Protocols Redefining Definition SWIFT’S GREATEST HITS
  • 30. protocol FullyNamed { var fullName: String {get} } Extensions & Protocols Redefining Definition SWIFT’S GREATEST HITS
  • 31. protocol FullyNamed { var fullName: String {get} } protocol Introducing: FullyNamed { func introduce() -> String } Extensions & Protocols Redefining Definition SWIFT’S GREATEST HITS
  • 32. protocol FullyNamed { var fullName: String {get} } protocol Introducing: FullyNamed { func introduce() -> String } extension Introducing { func introduce() -> String { return : "Hi, I’m (fullName)!” } } Extensions & Protocols Redefining Definition SWIFT’S GREATEST HITS
  • 33. protocol FullyNamed { var fullName: String {get} } protocol Introducing: FullyNamed { func introduce() -> String } extension Introducing { func introduce() -> String { return : "Hi, I’m (fullName)!” } } struct Person: Introducing { var fullName: String { return "(firstName) (lastName)" } } let p = Person(firstName: "Chad", lastName: "Moone") p.introduce() // "Hi, I'm Chad Moone!" Extensions & Protocols Redefining Definition SWIFT’S GREATEST HITS
  • 35. Optionality var myObject: Object = nil Make nil Great Again SWIFT’S GREATEST HITS
  • 36. Optionality var myObject: Object = nil myObject.toString() Make nil Great Again SWIFT’S GREATEST HITS
  • 37. var myObject: Object = nil myObject.toString() // <—- 💣💥💀 Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 38. Optionality var myObject: Object = nil Make nil Great Again SWIFT’S GREATEST HITS
  • 39. var myObject: Object = nil // <—- 🚨👾🚨* *👾 == “compiler” Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 40. var myObject: Object = Object() var optionalObject: Object? = nil Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 41. var myObject = Object() var optionalObject: Object? Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 42. var myObject = Object() var optionalObject: Object? myObject = nil Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 43. var myObject = Object() var optionalObject: Object? myObject = nil // <—- 🚨👾🚨 Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 44. var myObject = Object() var optionalObject: Object? myObject = otherObject // <—- ✅👾✅ Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 45. var myObject = Object() var optionalObject: Object? myObject = otherObject optionalObject = Object() optionalObject = nil Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 46. var myObject = Object() var optionalObject: Object? myObject = otherObject optionalObject = Object() Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 47. var myObject = Object() var optionalObject: Object? myObject = otherObject optionalObject = Object() myObject.print() optionalObject.print() Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 48. var myObject = Object() var optionalObject: Object? myObject = otherObject optionalObject = Object() myObject.print() // <—- guaranteed to be ✅ optionalObject.print() Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 49. var myObject = Object() var optionalObject: Object? myObject = otherObject optionalObject = Object() myObject.print() // <—- guaranteed to be ✅ optionalObject.print() // <—- 🚨👾🚨 Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 50. var myObject = Object() var optionalObject: Object? myObject = otherObject optionalObject = Object() myObject.print() // <—- guaranteed to be ✅ optionalObject?.print() Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 51. var myObject = Object() var optionalObject: Object? myObject = otherObject optionalObject = Object() myObject.print() // <—- guaranteed to be ✅ optionalObject?.print() // <—- has value, so ✅ Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 52. var myObject = Object() var optionalObject: Object? myObject = otherObject optionalObject = Object() myObject.print() // <—- guaranteed to be ✅ optionalObject?.print() // <—- has value, so ✅ optionalObject = nil optionalObject?.print() // <—- no value == no op Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 53. func setAlarm(time: Date, message: String?) { alarmTime = time if let message = message { message.uppercased() addExclamations(message) emojify(message) alarmMessage = message } } Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 54. func setAlarm(time: Date, message: String?) { alarmTime = time guard let message = message else { return } message.uppercased() addExclamations(message) emojify(message) alarmMessage = message } Optionality Make nil Great Again SWIFT’S GREATEST HITS
  • 55. 5 Enums & Generics Safe, yet flexible
  • 56. Enums & Generics enum CompassPoint { case north case south case east case west } var directionToHead = CompassPoint.west var directionToShore: CompassPoint = .east Safe, yet flexible SWIFT’S GREATEST HITS
  • 57. Enums & Generics switch directionToTravel { case .north: print("To Canada!") case .south: print("To Mexico!") } Safe, yet flexible SWIFT’S GREATEST HITS
  • 58. Enums & Generics switch directionToTravel { case .north: print("To Canada!") case .south: print("To Mexico!") } // <—- 🚨👾🚨 Must be exhaustive!! Safe, yet flexible SWIFT’S GREATEST HITS
  • 59. Enums & Generics switch directionToTravel { case .north: print("To Canada!") case .south: print("To Mexico!") default: print("Into the ocean!") } Safe, yet flexible SWIFT’S GREATEST HITS
  • 60. Enums & Generics enum Planet: Int { case mercury = 1 case venus = 2 case earth = 3 case mars = 4 case jupiter = 5 case saturn = 6 case uranus = 7 case neptune = 8 } Safe, yet flexible SWIFT’S GREATEST HITS
  • 61. Enums & Generics enum Planet: Int { case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune } Safe, yet flexible SWIFT’S GREATEST HITS
  • 62. Enums & Generics enum Planet: Int { case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune } if let somePlanet = Planet(rawValue: 11) { switch somePlanet { case .earth: print("Mostly harmless") default: print("Not a safe place for humans") } } else { print("There isn't a planet at position (positionToFind)") } // Prints "There isn't a planet at position 11" Safe, yet flexible SWIFT’S GREATEST HITS
  • 63. Enums & Generics enum Either { case str(String) case num(Double) } var a = Either.str("hello") a = .num(1.0) Safe, yet flexible SWIFT’S GREATEST HITS
  • 64. Enums & Generics enum Trade { case Buy(stock: String, amount: Int) case Sell(stock: String, amount: Int) } Safe, yet flexible SWIFT’S GREATEST HITS
  • 65. Enums & Generics enum Trade { case Buy(stock: String, amount: Int) case Sell(stock: String, amount: Int) } func executeTrade(_ trade: Trade) { /* magic */ } Safe, yet flexible SWIFT’S GREATEST HITS
  • 66. Enums & Generics enum Trade { case Buy(stock: String, amount: Int) case Sell(stock: String, amount: Int) } func executeTrade(_ trade: Trade) { /* magic */ } let purchase = Trade.Buy(stock: "AAPL", amount: 20) executeTrade(purchase) let sale = Trade.Sell(stock: "SNAP", amount: 500) executeTrade(sale) Safe, yet flexible SWIFT’S GREATEST HITS
  • 67. Enums & Generics enum Either { case str(String) case num(Double) } var a = Either.str("hello") a = .num(1.0) Safe, yet flexible SWIFT’S GREATEST HITS
  • 68. Enums & Generics enum Optional<Wrapped> { case some(Wrapped) case none } var possibleInteger: Optional<Int> = .none possibleInteger = .some(100) Safe, yet flexible SWIFT’S GREATEST HITS
  • 70. Automatic Reference Counting class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { print("Bye, (name)!") } } var p1: Person? = Person(name: "Chad") p1 = nil // "Bye, Chad” p1 = Person(name: "Murray") var p2 = p1 p1 = nil // Murray still has an active reference p2 = Person(name: "Bruce") // "Bye, Murray" The “other” ARC SWIFT’S GREATEST HITS
  • 71. Automatic Reference Counting class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { print("Bye, (name)!") } } class Apartment { let unit: String init(unit: String) { self.unit = unit } var tenant: Person? deinit { print("Apartment (unit) is being deinitialized") } } The “other” ARC SWIFT’S GREATEST HITS
  • 72. Automatic Reference Counting class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { print("Bye, (name)!") } } class Apartment { let unit: String init(unit: String) { self.unit = unit } var tenant: Person? deinit { print("Apartment (unit) is being deinitialized") } } var p: Person? = Person(name: "Chad") var a: Apartment? = Apartment(unit: "5C") p?.apartment = a a?.tenant = p p = nil // a still has a reference a = nil // p still has a reference The “other” ARC SWIFT’S GREATEST HITS
  • 73. Automatic Reference Counting class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { print("Bye, (name)!") } } class Apartment { let unit: String init(unit: String) { self.unit = unit } weak var tenant: Person? deinit { print("Apartment (unit) is being deinitialized") } } var p: Person? = Person(name: "Chad") var a: Apartment? = Apartment(unit: "5C") p?.apartment = a a?.tenant = p The “other” ARC SWIFT’S GREATEST HITS
  • 74. Automatic Reference Counting class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { print("Bye, (name)!") } } class Apartment { let unit: String init(unit: String) { self.unit = unit } weak var tenant: Person? deinit { print("Apartment (unit) is being deinitialized") } } var p: Person? = Person(name: "Chad") var a: Apartment? = Apartment(unit: "5C") p?.apartment = a a?.tenant = p p = nil // "Bye, Chad!" a = nil // "Apartment 5C is being deinitialized" The “other” ARC SWIFT’S GREATEST HITS
  • 76. Swift Playgrounds • For macOS & iPad • Start playing with the full power of swift in seconds • Tons of tutorials and other resources • REPL on Steroids
  • 79.
  • 80.
  • 81.
  • 82.
  • 84. Swift Playgrounds • For macOS & iPad • Start playing with the full power of swift in seconds • Tons of tutorials and other resources • REPL on Steroids
  • 85. • swift.org • developer.apple.com/swift • github.com/apple/swift • Free Swift programming book series (regularly updated) Getting Started

Notas del editor

  1. mention objc
  2. Swift forces you to address the fact that this value may or may not be nil uses syntactic sugar
  3. Rules apply to all types—primitives and other value types as well as reference types Introduces a new way of thinking, particularly with regards to default values