SlideShare a Scribd company logo
Swift,
functional programming,
& the future of Objective-C
Alexis Gallagher
@alexisgallagherPart of a talk delivered on 2014-07-02
Ques%ons
1. What's)new)in)Swi.?
2. Is)Swi.)a)func5onal)programming)language?
• And)what)is)"func5onal",)anyway?)Who)cares?
3. Is)ObjC)going)away?
• And)so,)is)everything)easier)now?
What's'hardly'new'in'Swi,?
Objective-C
• classes
• methods
• protocols
• categories
• functions
• ARC
• blocks
• Cocoa values 

& collections
Objective-C
Swift
• classes
• methods
• protocols
• extensions
• functions
• ARC
• closures
• Cocoa values 

& collections
just%syntax,%almost
ObjC:
// Foo.h
@interface Foo : UIView
@property (nonatomic,weak) UIView * myView
@end
@implementation Foo
- (CGFloat) addAtX:(CGFloat) x andY:(CGFloat) y {
UIView * v = [[UIView alloc] initWithFrame:CGRectMake(x,y,10,10)];
[self addSubview:v];
self.myView = v;
return x + y;
}
@end
just%syntax,%almost
Swi$:
class Foo: UIView {
weak var myView:UIView?
func addAt(#x:CGFloat, y:CGFloat) -> CGFloat {
let v = UIView(frame:CGRectMake(x,y,10,10))
self.addSubview(v)
self.myView = v
return x + y
}
}
blocks'(closures)
ObjC:
NSInteger (^increment)(NSInteger) = ^NSInteger (NSInteger x) {
return x+1;
}
Swi$:
let increment = {
(x:NSInteger) -> NSInteger in
return x+1
}
What's'a'bit$new'in'Swi,?
Objective-C
• structs
• namespaces
• operator
overloading
• ObjC interop
• Swift values &
collections
Swift+Swift
• classes
• methods
• protocols
• extensions
• functions
• ARC
• closures
• Cocoa values 

& collections
structs&are&peers&to&classes
ObjC:
CGRect r = [view frame];
CGFloat intTopY = CGRectGetMinY(CGRectIntegral(r));
Swi$:
extension CGRect {
func intTopY() -> CGFloat {
return CGRectGetMinY(CGRectIntegral(self))
}
}
let r = view.frame;
let intTopY = r.intTopY;
What's'really&new'in'Swi,?
Objective-C
• enums with associated values
• option types
• pattern matching
• generics
• type inference
• immutability supports
• tuples
Swift+
• structs
• namespaces
• operator
overloading
• ObjC interop
• Swift values &
collections
Swift+Swift
• classes
• methods
• protocols
• extensions
• functions
• ARC
• closures
• Cocoa values 

& collections
Objective-C
• enums with associated values
• option types
• pattern matching
• generics
• type inference
• immutability supports
• tuples
Swift+
• structs
• namespaces
• operator
overloading
• ObjC interop
• Swift values &
collections
Swift+Swift
• classes
• methods
• protocols
• extensions
• functions
• ARC
• closures
• Cocoa values 

& collections
Every “really new” part of Swift
originated in a functional programming
language of the 1980s or earlier.
FP
No#ma&er#what#language#you#work#
in,#programming#in#a#func7onal#style#
provides#benefits.#You#should#do#it#
whenever#it#is#convenient....
—"John"Carmack,"2012.
JavaScript*is*brilliant*and*is*
succeeding*...*and*I*think*it's*because*
of*the*func:onal*stuff.
—"Douglas"Crockford,"2014
a"programming"style
trea%ng(the
func%on
as#the#primary#unit#of#abstrac2on
t0 = 5
f(t0) = 50
NSNumber * t0 = @5;
NSNumber * pos = f(t0);
pos; // => 50
f(t0) = 50 pos = f(t0);
pos; //=> 100; (surprise!)
computational functions

do things
mathematical functions"
establish true relations
which remain true
mathematical variables"
are names
we give to values
t0 = 5
t0 = 5
t0 = 6
computational variables"
are like names for places,
whose contents can change
NSNumber * five = @5;
five = @6; // ?!
five = @7;
[five setIntegerValue:8]; // ?! ?!
FP style boils down to
• Restrictions to emulate the
predictability of mathematical
functions and variables
• Idioms to use functions for all
abstraction — in defining other
functions, in hiding information, etc.
• (Sometimes) type systems to
provide compile-time checks on the
values moving through functions
• purity and immutability guarantees



• function literals
• function closures
• functions as first-class values

• enums (aka, sum types, tagged unions)
• algebraic data types
• type inference
• fancy types: first-order, recursive, 

dependent, higher-kinded, constrained, 

etc..
FEATURES
• Idioms
• combine, pass, & return

functions like other values
• Restrictions
• pure functions
• immutable data
• Type systems (sometimes)
• to check valid values
STYLE
supported by
Haskell (1988)
Scheme (1975)
SML (1984)
ML (1973)
Scala (2003)
OCaml (1996)
Clojure (2009)
F# (2005)
Erlang (1986)
dynamic static
Coq, Agda, Idris
So is Swift “functional”?
Haskell SML Scheme Clojure Swift ObjC
purity & immutability help Yes, very. Y Y Y Y meh
function literals, closures,
first-classness
Y Y Y Y Y meh
expression-oriented Y Y Y Y N N
proper tail calls Y Y Y N ? ?
memory management Y Y Y Y meh meh
generics Y Y N N Y N
enum types Y Y N N Y N
type inference Y Y N N Y N
algebraic data types Y Y N N ? N
super DUPER fancy types Y ? N N N N
If this were 1998 

Swift would be a
niche functional language
If this were 1998 

Swift would be a
niche functional language
… but maybe we’re all functional now? or could be?
Should we care?
functional Swift: 

(embarrassingly trivial) HOFs
Higher'order*func/ons:*filter
ObjC:
NSArray * inArray = @[@"Hello",@"Ciao"];
NSArray * outArray = [inArray filteredArrayUsingPredicate:
[NSPredicate predicateWithBlock:
^BOOL(NSString * item, NSDictionary *bindings) {
return [item hasPrefix:@"Hello"];
}]];
Swi$:
let inArray = ["Hello","Ciao"];
let outArray = inputArray.filter({ $0.hasPrefix("Hello") })
Higher'order*func/ons:*map
ObjC:
NSArray * inArray = @[@"John Appleseed", @"Sally Appleseed"];
NSMutableArray * outArray = [NSMutableArray array];
for (NSString * name in inArray) {
[outArray addObject:[name componentsSeparatedByString:@" "][0]];
}
Swi$:
let inArray = ["John Appleseed", "Sally Appleseed"];
let outArray = inArray.map({ $0.componentsSeparatedByString(" ")[0] })
Higher'order*func/ons:*reduce
reduce!is!a!HOF!for!processing!a!collec1on!into!a!single!value.
Swi$:
let x = [1,2,3,4]
let sum = x.reduce(0, +);
sum // => 7
let product = x.reduce(1, *);
product //=> 24
Closures: variable capture on purpose
func makeCounter() -> (() -> NSInteger) {!
var x = 0!
func increment() -> NSInteger {!
x = x + 1;!
return x;!
}!
return increment;!
}!
!
var counter1 = makeCounter()!
var counter2 = makeCounter()!
!
counter1() //=> 1!
counter1() //=> 2!
counter1() //=> 3!
!
counter2() //=> 1!
functional Swift: 

JSON as ADT
JSON
NSJSONSerialization Class Reference
… 
An object that may be converted to JSON must have the following
properties:

•
The top level object is an NSArray or NSDictionary.

•
All objects are instances of NSString, NSNumber, NSArray,
NSDictionary, or NSNull.

•
All dictionary keys are instances of NSString.

•
Numbers are not NaN or infinity.
!
Other rules may apply. Calling isValidJSONObject: or attempting a
conversion are the definitive ways to tell if a given object can be
converted to JSON data.
JSON%as%algebraic%data%type
Enumera(on*with*associated*values
enum JSONValue {
case JNumber(NSNumber)
case JString(String)
case JBool(Bool)
case JNull
case JArray(Array<JSONValue>)
case JObject(Dictionary<String,JSONValue>)
case JInvalid(NSError)
// ...
}
Source:(h*ps://github.com/lingoer/Swi7yJSON
functional Swift: 

Improving on NSError
NSError&is&ugly
ObjC:
NSError *error;
NSData *data = [NSData dataWithContentsOfFile:file options:0 error:&error];
if(data == nil) {
// handle error
}
Either'type
Swi$:
enum DataResult {
case Success(NSData)
case Error(NSError)
// ...
}
switch NSData(contentsOfFile:file, options:0) {
case .Success(let data):
// handle data here then return
case .Error(let error):
// handle error here then return
}
SwiftZ (by maxpow4h)
Either and Result:!
//	
  Result	
  represents	
  something	
  that	
  could	
  work	
  or	
  be	
  an	
  NSError.	
  
//	
  Say	
  we	
  have	
  2	
  functions,	
  the	
  first	
  fetches	
  from	
  a	
  web	
  services,	
  
//	
  the	
  second	
  decodes	
  the	
  string	
  into	
  a	
  User.	
  
//	
  Both	
  *could*	
  fail	
  with	
  an	
  NSError,	
  so	
  we	
  use	
  a	
  Result<A>.	
  
func	
  getWeb()	
  -­‐>	
  Result<String>	
  {	
  
	
  	
  var	
  e:	
  NSError?	
  
	
  	
  let	
  str	
  =	
  doStuff("foo",	
  e)	
  
	
  	
  return	
  Result(e,	
  str)	
  
}	
  
!
func	
  decodeWeb(str:	
  String)	
  -­‐>	
  Result<User>	
  {	
  
	
  	
  var	
  e:	
  NSError?	
  
	
  	
  let	
  user	
  =	
  decode(str,	
  e)	
  
	
  	
  return	
  Result(e,	
  user)	
  
}	
  
!
//	
  We	
  can	
  compose	
  these	
  two	
  functions	
  with	
  the	
  `>>=`	
  function.	
  
!
let	
  getUser:	
  Result<User>	
  =	
  getWeb()	
  >>=	
  decodeWeb	
  
!
switch	
  (getUser)	
  {	
  
	
  	
  case	
  let	
  .Error(e):	
  println("NSError:	
  (e)")	
  
	
  	
  case	
  let	
  .Value(user):	
  println(user.name)	
  
Is ObjC going away? 

Is it “easier” now?
Objective-C
• enums with associated values
• option types
• pattern matching
• generics
• type inference
• immutability supports
• tuples
Swift+
• structs
• namespaces
• operator
overloading
• ObjC interop
• Swift values &
collections
Swift+Swift
• classes
• methods
• protocols
• extensions
• functions
• ARC
• closures
• Cocoa values 

& collections
–"Advanced Swift Debugging in LLDB", WWDC2014, session 410, 20m—28m.
“Objective-C isn't really going anywhere.... Even if you start a
brand new Swift app for the first time today after this session,
you're going to use Cocoa, or Cocoa Touch. You're going to
import Foundation. You're going to import UIKit. Those
frameworks are written in Objective-C. That means, wherever you
look around, there's going to be Objective-C in the picture.
And you're going to have to deal with debugging mixed Swift /
Objective-C situations..”
Canaries in the ObjC coal mine
• Swift achieves genuine C-like performance
• Swift-only types appearing at public API boundaries
• Deprecation of the ObjC runtime’s more dynamic features
• GitHub RAC devs (jspahrsummers, joshaber, & others)
• ReactiveCocoa. This work is indirectly influenced by typed FP.

<https://github.com/ReactiveCocoa/ReactiveCocoa>
• Maxwell Swadling
• SwiftZ. Currently translating lots of typed FP idioms into a Swift library. 

<https://github.com/maxpow4h/swiftz>
• David Nolen.
• Om. Functional approach to writing GUIs in the browser, using ClojureScript with
Facebook’s React, leveraging CSP-style concurrency. Untyped FP.

<http://swannodette.github.io/2013/12/17/the-future-of-javascript-mvcs/>
• Upcoming book from ObjC.io authors.
@end
• Videos, notes, and homework from the Coursera “Programming
Languages” course, a great intro to Scheme, SML, and Ruby.

<https://class.coursera.org/proglang-2012-001>
• Interesting way to do SICP: http://understudyapp.com
• The talks by Rich Hickey (inventor of Clojure) are very rich

More Related Content

What's hot

Swift in SwiftUI
Swift in SwiftUISwift in SwiftUI
Swift in SwiftUI
Bongwon Lee
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
Kazunobu Tasaka
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8James Brown
 
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
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar
 
Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)
David de Boer
 
Contracts in-clojure-pete
Contracts in-clojure-peteContracts in-clojure-pete
Contracts in-clojure-pete
jessitron
 
Introduction to Clean Code
Introduction to Clean CodeIntroduction to Clean Code
Introduction to Clean Code
Julio Martinez
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
Nikita Popov
 
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
James Titcumb
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
Reem Alattas
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
Luis Atencio
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance Trivia
Nikita Popov
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
Hugo Firth
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
Fwdays
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
Ganesh Samarthyam
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Codemotion
 

What's hot (20)

Swift in SwiftUI
Swift in SwiftUISwift in SwiftUI
Swift in SwiftUI
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-C
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)Being functional in PHP (DPC 2016)
Being functional in PHP (DPC 2016)
 
Contracts in-clojure-pete
Contracts in-clojure-peteContracts in-clojure-pete
Contracts in-clojure-pete
 
Introduction to Clean Code
Introduction to Clean CodeIntroduction to Clean Code
Introduction to Clean Code
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?Typed Properties and more: What's coming in PHP 7.4?
Typed Properties and more: What's coming in PHP 7.4?
 
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
PHP Performance Trivia
PHP Performance TriviaPHP Performance Trivia
PHP Performance Trivia
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 

Similar to Swift, functional programming, and the future of Objective-C

A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
Matt Stine
 
Angular2 for Beginners
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
Oswald Campesato
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton Sheppard
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
Codemotion
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
Eduard Tomàs
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
LovelitJose
 
Introductionto fp with groovy
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovy
Isuru Samaraweera
 
Groovy unleashed
Groovy unleashed Groovy unleashed
Groovy unleashed
Isuru Samaraweera
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreWeb Zhao
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
Eric Pederson
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
JAX London
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersMiles Sabin
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
Miles Sabin
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
Movel
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?
Mario Camou Riveroll
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
Jarrod Overson
 

Similar to Swift, functional programming, and the future of Objective-C (20)

A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
 
Angular2 for Beginners
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
Introductionto fp with groovy
Introductionto fp with groovyIntroductionto fp with groovy
Introductionto fp with groovy
 
Groovy unleashed
Groovy unleashed Groovy unleashed
Groovy unleashed
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?
 
JavaScript and the AST
JavaScript and the ASTJavaScript and the AST
JavaScript and the AST
 

Recently uploaded

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 

Recently uploaded (20)

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 

Swift, functional programming, and the future of Objective-C

  • 1. Swift, functional programming, & the future of Objective-C Alexis Gallagher @alexisgallagherPart of a talk delivered on 2014-07-02
  • 2. Ques%ons 1. What's)new)in)Swi.? 2. Is)Swi.)a)func5onal)programming)language? • And)what)is)"func5onal",)anyway?)Who)cares? 3. Is)ObjC)going)away? • And)so,)is)everything)easier)now?
  • 4. Objective-C • classes • methods • protocols • categories • functions • ARC • blocks • Cocoa values 
 & collections
  • 5. Objective-C Swift • classes • methods • protocols • extensions • functions • ARC • closures • Cocoa values 
 & collections
  • 6. just%syntax,%almost ObjC: // Foo.h @interface Foo : UIView @property (nonatomic,weak) UIView * myView @end @implementation Foo - (CGFloat) addAtX:(CGFloat) x andY:(CGFloat) y { UIView * v = [[UIView alloc] initWithFrame:CGRectMake(x,y,10,10)]; [self addSubview:v]; self.myView = v; return x + y; } @end
  • 7. just%syntax,%almost Swi$: class Foo: UIView { weak var myView:UIView? func addAt(#x:CGFloat, y:CGFloat) -> CGFloat { let v = UIView(frame:CGRectMake(x,y,10,10)) self.addSubview(v) self.myView = v return x + y } }
  • 8. blocks'(closures) ObjC: NSInteger (^increment)(NSInteger) = ^NSInteger (NSInteger x) { return x+1; } Swi$: let increment = { (x:NSInteger) -> NSInteger in return x+1 }
  • 10. Objective-C • structs • namespaces • operator overloading • ObjC interop • Swift values & collections Swift+Swift • classes • methods • protocols • extensions • functions • ARC • closures • Cocoa values 
 & collections
  • 11. structs&are&peers&to&classes ObjC: CGRect r = [view frame]; CGFloat intTopY = CGRectGetMinY(CGRectIntegral(r)); Swi$: extension CGRect { func intTopY() -> CGFloat { return CGRectGetMinY(CGRectIntegral(self)) } } let r = view.frame; let intTopY = r.intTopY;
  • 13. Objective-C • enums with associated values • option types • pattern matching • generics • type inference • immutability supports • tuples Swift+ • structs • namespaces • operator overloading • ObjC interop • Swift values & collections Swift+Swift • classes • methods • protocols • extensions • functions • ARC • closures • Cocoa values 
 & collections
  • 14. Objective-C • enums with associated values • option types • pattern matching • generics • type inference • immutability supports • tuples Swift+ • structs • namespaces • operator overloading • ObjC interop • Swift values & collections Swift+Swift • classes • methods • protocols • extensions • functions • ARC • closures • Cocoa values 
 & collections
  • 15. Every “really new” part of Swift originated in a functional programming language of the 1980s or earlier.
  • 16. FP
  • 20. t0 = 5 f(t0) = 50 NSNumber * t0 = @5; NSNumber * pos = f(t0); pos; // => 50 f(t0) = 50 pos = f(t0); pos; //=> 100; (surprise!) computational functions
 do things mathematical functions" establish true relations which remain true
  • 21. mathematical variables" are names we give to values t0 = 5 t0 = 5 t0 = 6 computational variables" are like names for places, whose contents can change NSNumber * five = @5; five = @6; // ?! five = @7; [five setIntegerValue:8]; // ?! ?!
  • 22. FP style boils down to • Restrictions to emulate the predictability of mathematical functions and variables • Idioms to use functions for all abstraction — in defining other functions, in hiding information, etc. • (Sometimes) type systems to provide compile-time checks on the values moving through functions
  • 23. • purity and immutability guarantees
 
 • function literals • function closures • functions as first-class values
 • enums (aka, sum types, tagged unions) • algebraic data types • type inference • fancy types: first-order, recursive, 
 dependent, higher-kinded, constrained, 
 etc.. FEATURES • Idioms • combine, pass, & return
 functions like other values • Restrictions • pure functions • immutable data • Type systems (sometimes) • to check valid values STYLE supported by
  • 24. Haskell (1988) Scheme (1975) SML (1984) ML (1973) Scala (2003) OCaml (1996) Clojure (2009) F# (2005) Erlang (1986) dynamic static Coq, Agda, Idris
  • 25. So is Swift “functional”?
  • 26. Haskell SML Scheme Clojure Swift ObjC purity & immutability help Yes, very. Y Y Y Y meh function literals, closures, first-classness Y Y Y Y Y meh expression-oriented Y Y Y Y N N proper tail calls Y Y Y N ? ? memory management Y Y Y Y meh meh generics Y Y N N Y N enum types Y Y N N Y N type inference Y Y N N Y N algebraic data types Y Y N N ? N super DUPER fancy types Y ? N N N N
  • 27. If this were 1998 
 Swift would be a niche functional language
  • 28. If this were 1998 
 Swift would be a niche functional language … but maybe we’re all functional now? or could be?
  • 31. Higher'order*func/ons:*filter ObjC: NSArray * inArray = @[@"Hello",@"Ciao"]; NSArray * outArray = [inArray filteredArrayUsingPredicate: [NSPredicate predicateWithBlock: ^BOOL(NSString * item, NSDictionary *bindings) { return [item hasPrefix:@"Hello"]; }]]; Swi$: let inArray = ["Hello","Ciao"]; let outArray = inputArray.filter({ $0.hasPrefix("Hello") })
  • 32. Higher'order*func/ons:*map ObjC: NSArray * inArray = @[@"John Appleseed", @"Sally Appleseed"]; NSMutableArray * outArray = [NSMutableArray array]; for (NSString * name in inArray) { [outArray addObject:[name componentsSeparatedByString:@" "][0]]; } Swi$: let inArray = ["John Appleseed", "Sally Appleseed"]; let outArray = inArray.map({ $0.componentsSeparatedByString(" ")[0] })
  • 33. Higher'order*func/ons:*reduce reduce!is!a!HOF!for!processing!a!collec1on!into!a!single!value. Swi$: let x = [1,2,3,4] let sum = x.reduce(0, +); sum // => 7 let product = x.reduce(1, *); product //=> 24
  • 34. Closures: variable capture on purpose func makeCounter() -> (() -> NSInteger) {! var x = 0! func increment() -> NSInteger {! x = x + 1;! return x;! }! return increment;! }! ! var counter1 = makeCounter()! var counter2 = makeCounter()! ! counter1() //=> 1! counter1() //=> 2! counter1() //=> 3! ! counter2() //=> 1!
  • 36. JSON NSJSONSerialization Class Reference … An object that may be converted to JSON must have the following properties: • The top level object is an NSArray or NSDictionary. • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull. • All dictionary keys are instances of NSString. • Numbers are not NaN or infinity. ! Other rules may apply. Calling isValidJSONObject: or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.
  • 37. JSON%as%algebraic%data%type Enumera(on*with*associated*values enum JSONValue { case JNumber(NSNumber) case JString(String) case JBool(Bool) case JNull case JArray(Array<JSONValue>) case JObject(Dictionary<String,JSONValue>) case JInvalid(NSError) // ... } Source:(h*ps://github.com/lingoer/Swi7yJSON
  • 39. NSError&is&ugly ObjC: NSError *error; NSData *data = [NSData dataWithContentsOfFile:file options:0 error:&error]; if(data == nil) { // handle error }
  • 40. Either'type Swi$: enum DataResult { case Success(NSData) case Error(NSError) // ... } switch NSData(contentsOfFile:file, options:0) { case .Success(let data): // handle data here then return case .Error(let error): // handle error here then return }
  • 41. SwiftZ (by maxpow4h) Either and Result:! //  Result  represents  something  that  could  work  or  be  an  NSError.   //  Say  we  have  2  functions,  the  first  fetches  from  a  web  services,   //  the  second  decodes  the  string  into  a  User.   //  Both  *could*  fail  with  an  NSError,  so  we  use  a  Result<A>.   func  getWeb()  -­‐>  Result<String>  {      var  e:  NSError?      let  str  =  doStuff("foo",  e)      return  Result(e,  str)   }   ! func  decodeWeb(str:  String)  -­‐>  Result<User>  {      var  e:  NSError?      let  user  =  decode(str,  e)      return  Result(e,  user)   }   ! //  We  can  compose  these  two  functions  with  the  `>>=`  function.   ! let  getUser:  Result<User>  =  getWeb()  >>=  decodeWeb   ! switch  (getUser)  {      case  let  .Error(e):  println("NSError:  (e)")      case  let  .Value(user):  println(user.name)  
  • 42. Is ObjC going away? 
 Is it “easier” now?
  • 43. Objective-C • enums with associated values • option types • pattern matching • generics • type inference • immutability supports • tuples Swift+ • structs • namespaces • operator overloading • ObjC interop • Swift values & collections Swift+Swift • classes • methods • protocols • extensions • functions • ARC • closures • Cocoa values 
 & collections
  • 44. –"Advanced Swift Debugging in LLDB", WWDC2014, session 410, 20m—28m. “Objective-C isn't really going anywhere.... Even if you start a brand new Swift app for the first time today after this session, you're going to use Cocoa, or Cocoa Touch. You're going to import Foundation. You're going to import UIKit. Those frameworks are written in Objective-C. That means, wherever you look around, there's going to be Objective-C in the picture. And you're going to have to deal with debugging mixed Swift / Objective-C situations..”
  • 45. Canaries in the ObjC coal mine • Swift achieves genuine C-like performance • Swift-only types appearing at public API boundaries • Deprecation of the ObjC runtime’s more dynamic features
  • 46. • GitHub RAC devs (jspahrsummers, joshaber, & others) • ReactiveCocoa. This work is indirectly influenced by typed FP.
 <https://github.com/ReactiveCocoa/ReactiveCocoa> • Maxwell Swadling • SwiftZ. Currently translating lots of typed FP idioms into a Swift library. 
 <https://github.com/maxpow4h/swiftz> • David Nolen. • Om. Functional approach to writing GUIs in the browser, using ClojureScript with Facebook’s React, leveraging CSP-style concurrency. Untyped FP.
 <http://swannodette.github.io/2013/12/17/the-future-of-javascript-mvcs/> • Upcoming book from ObjC.io authors.
  • 47.
  • 48. @end
  • 49. • Videos, notes, and homework from the Coursera “Programming Languages” course, a great intro to Scheme, SML, and Ruby.
 <https://class.coursera.org/proglang-2012-001> • Interesting way to do SICP: http://understudyapp.com • The talks by Rich Hickey (inventor of Clojure) are very rich