Swift - Modern & Expressive, or Magical Unicorn?

Mike Jones
Mike JonesCreative Technologist
Modern & Expressive or Magical Unicorn?
Mike Jones - @FlashGen
Swift…
@flashgen | #reasonsto
A point of reference, of
sorts…
@flashgen | #reasonsto
@flashgen | #reasonsto
var myNamevar = “Mike Jones”:String ;
@flashgen | #reasonsto
var myName = “Mike Jones”
@flashgen | #reasonsto
var myName:String = “Mike Jones”;
var myName = “Mike Jones”
@flashgen | #reasonsto
var myName = “Mike Jones”
let myName = “Mike Jones”
@flashgen | #reasonsto
Loops
Loops
for var i = 0; i < 10; i++
{
println(i)
}
Loops
for i in 0..<10
{
println(i)
}
Loops
var myArray = [1,2,3,4,5]
for item in myArray
{
println(item)
}
Loops
var i = 1
while i < 10
{
println(i)
i++
}
Loops
var i = 10
do
{
println(i)
i++
}
while i < 10
@flashgen | #reasonsto
Conditionals
If…else
var num = 10
if num < 20
{
println(“less than 20")
}
else
{
println("not less than 20")
}
Switch…Case
var value = 10
switch value
{
case 10:
println("Yay! just right")
case 20:
println("a bit too high")
default:
println("Nothing to see here")
}
Switch…Case
var value = 6
switch value
{
case 1...9:
println("Too low")
case 10:
println("Yay! just right")
case 20:
println("a bit too high")
default:
println("Nothing to see here")
}
@flashgen | #reasonsto
Optionals…
@flashgen | #reasonsto
Optionals
var optionalInteger: Int?
var optionalInteger: Optional<Int>
Optionals
var impUnwrappedString:String!
var impUnwrappedString:ImplicitlyUnwrappedOptional<String>
Optionals
var myString = “hello”
var myInt = myString.toInt()
Optionals
var myString = “hello”
var myInt = myString.toInt()
// myInt = nil
Optionals
var myString = “3”
var myInt = myString.toInt()
Optionals
var myString = “3”
var myInt = myString.toInt()
// myInt = 3
Optionals
var myString = “3”
var myInt:Int = myString.toInt()
Optionals
var myString = “3”
var myInt:Int = myString.toInt()
// Object of type Optional is not unwrapped
Optionals
var myString = “3”
var myInt:Int = myString.toInt()!
Optionals
var myString = “3”
var myInt:Int = myString.toInt()!
// myInt = 3
Optionals
var myString = "hello"
var myInt:Int = myString.toInt()!.advancedBy(5)
Optionals
var myString = "hello"
var myInt:Int = myString.toInt()!.advancedBy(5)
// This fails
Optionals
var myString = "5"
var myOtherInt:Int = 0;
if let myInt = myString.toInt()?.advancedBy(5)
{
myOtherInt = myInt;
}
else
{
println("It's nil")
}
@flashgen | #reasonsto
Functions & Closures
Functions
func myFunc(valA:Int, valB:Int) -> Int
{
return valA + valB
}
var myInt = myFunc(4, 4);
Functions
func myFunc(#valA:Int, #valB:Int) -> Int
{
return valA + valB
}
var myInt = myFunc(valA:4, valB:4);
Functions
func myFunc(myAge valA:Int, yourAge valB:Int) -> Int
{
return valA + valB
}
var ourAgesCombined = myFunc(myAge:4, yourAge:4);
Tuples
func sayHello(greeting:String, name:String) -> (String, String)
{
return (greeting + " " + name, “Pleased to meet you :)”)
}
var mygreeting = sayHello("Hello", "Reasons");
mygreeting.0; // Hello Reasons
mygreeting.1; // Pleased to meet you :)
Tuples
func sayHello(greeting:String, name:String) ->
(fullGreeting:String, response:String)
{
return (greeting + " " + name, “Pleased to meet you :)”)
}
var mygreeting = sayHello("Hello", "Reasons");
mygreeting.fullGreeting; // Hello Reasons
mygreeting.response; // Pleased to meet you :)
Tuples
func sayHello(greeting:String, name:String) -> (String, String)
{
return (greeting + " " + name, "Pleased to meet you :)")
}
let (fullGreeting, response) = sayHello("Hello", "Reasons");
fullGreeting; // Hello Reasons
response; // Pleased to meet you :)
Tuples
func sayHello(greeting:String, name:String) -> (String, String)
{
return (greeting + " " + name, "Pleased to meet you :)")
}
let (fullGreeting, _) = sayHello("Hello", "Reasons");
fullGreeting; // Hello Reasons
Variadic Functions
func addNumbers(numbers:Int...) -> Int
{
var total = 0;
for num in numbers
{
total += num
}
return total;
}
addNumbers(1,2,3,4,5) // 15
addNumbers(1,2,3) // 6
Function Types
func myFunc(valA:Int, valB:Int) -> Int
{
return valA + valB
}
var myIntFunc :(Int, Int) -> Int = myFunc
myIntFunc(4,4)
Closures
var namesArray = ["Mike", "Jason", "Dennis", "Darren", "John"];
func sortAlphabetically (s1:String, s2:String) -> Bool
{
return s1 < s2;
}
let myFriends = sorted(namesArray, sortAlphabetically)
Closures
var namesArray = ["Mike", "Darren", "Dennis", "Jason", "Macca"];
let myFriends = sorted(namesArray,
{ (s1:String, s2:String) -> Bool in
return s1 < s2;
})
in…out
var month = 9
var year = 2015
func swapTwoInts(inout a: Int, inout b: Int)
{
let tempA = a
a = b
b = tempA
}
swapTwoInts(&month, &year)
// month = 2015, year = 9
@flashgen | #reasonsto
Structs, Classes,
Protocols & Extensions
@flashgen | #reasonsto
Structs
Structs
struct Person
{
var firstName: String = "Mike";
var lastName: String = "Jones";
}
let myPerson = Person()
Classes
class Person
{
var firstName: String;
var lastName: String;
init(fName:String, lName:String)
{
firstName = fName;
lastName = lName;
}
}
let myPerson = Person(fName:"Mike", lName:"Jones")
Classes
class Person
{
var firstName: String;
var lastName: String;
init(fName:String="John", lName:String="Smith")
{
firstName = fName;
lastName = lName;
}
}
let myPerson = Person(fName:"Mike", lName:”Jones”)
// fName = "Mike", lName = "Jones"
let myDefaultPerson = Person()
// fName = "John", lName = "Smith"
Classes
class Person
{
var firstName: String;
var lastName: String;
init(fName:String, lName:String)
{
firstName = fName;
lastName = lName;
}
convenience init()
{
self.init(fName: "John", lName: "Smith");
}
}
let myPerson = Person() // fName = "John", lName = "Smith"
Classes
class Person
{
var firstName: String;
var lastName: String;
init(fName:String, lName:String)
{
firstName = fName;
lastName = lName;
}
deinit
{
// Clean up here
}
}
Classes
class Person
{
var firstName: String;
var lastName: String;
var fullName:String
{
get
{
return self.firstName + " " + self.lastName
}
}
// …
}
Inheritance
class Employee: Person
{
var jobDescription :String = "I'm a developer";
func whatAreYouDoing() -> String
{
return "I'm working."
}
}
Inheritance
public class Manager: Employee
{
override var jobDescription :String
{
get
{
return super.jobDescription
}
set(value)
{
super.jobDescription = value;
}
}
override func whatAreYouDoing() -> String
{
return "Very little - I'm the boss!"
}
}
@flashgen | #reasonsto
Protocols
Protocols
protocol UnicornsProt
{
var unicornHerd:Int? { get set }
func howManyUnicornsDoYouOwn() -> Int?
}
Protocols
class Person: UnicornsProt
{
var unicornHerd: Int?;
func howManyUnicornsDoYouOwn() -> Int?
{
return unicornHerd;
}
}
@flashgen | #reasonsto
Extensions
Extensions
extension Person
{
public var unicorns:String { return "UNICORNS!" }
public func moreUnicorns() -> String
{
return “MORE " + unicorns;
}
}
@flashgen | #reasonsto
Generics…
Generics
var myArray :Array<String>
var myDict :Dictionary<String, Person>
var myOptionalInt :Optional<Int>
Generics
func swapTwoInts(inout a: Int, inout b: Int)
{
let tempA = a
a = b
b = tempA
}
func swapTwoStrings(inout a: String, inout b: String)
{
let tempA = a
a = b
b = tempA
}
func swapTwoDoubles(inout a: Double, inout b: Double)
{
let tempA = a
a = b
b = tempA
}
Generics
var month = 9
var year = 2015
var greeting = "Hello Reasons"
var response = "Pleased to meet you :)"
func swapTwoValues<T>(inout a: T, inout b: T)
{
let tempA = a
a = b
b = tempA
}
swapTwoValues(&month, &year)
// month = 2015, year = 9
swapTwoValues(&greeting, &response)
// greeting = "Pleased to meet you :)
// response = "Hello Reasons
@flashgen | #reasonsto
one more thing…
@flashgen | #reasonsto
Swift 2.0
@flashgen | #reasonsto
Open Source
@flashgen | #reasonsto
Apple Developer Program
http://developer.apple.com
@flashgen | #reasonsto
Thank You
Mike Jones
pixadecimal.com
blog.flashgen.com
@FlashGen
1 of 70

Recommended

Total World Domination with i18n (es) by
Total World Domination with i18n (es)Total World Domination with i18n (es)
Total World Domination with i18n (es)Zé Fontainhas
504 views47 slides
Ruby by
RubyRuby
RubyDenis Defreyne
1K views120 slides
Functional Pe(a)rls - the Purely Functional Datastructures edition by
Functional Pe(a)rls - the Purely Functional Datastructures editionFunctional Pe(a)rls - the Purely Functional Datastructures edition
Functional Pe(a)rls - the Purely Functional Datastructures editionosfameron
912 views82 slides
Derping With Kotlin by
Derping With KotlinDerping With Kotlin
Derping With KotlinRoss Tuck
614 views71 slides
Functional pe(a)rls: Huey's zipper by
Functional pe(a)rls: Huey's zipperFunctional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperosfameron
1.4K views111 slides
Optionals Swift - Swift Paris Junior #3 by
Optionals Swift - Swift Paris Junior #3 Optionals Swift - Swift Paris Junior #3
Optionals Swift - Swift Paris Junior #3 LouiseFonteneau
29 views54 slides

More Related Content

What's hot

Is Haskell an acceptable Perl? by
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?osfameron
1.6K views87 slides
Desenvolvimento web usando django by
Desenvolvimento web usando djangoDesenvolvimento web usando django
Desenvolvimento web usando djangoyurimalheiros
1.3K views110 slides
みんなで Swift 復習会での談笑用スライド – 3rd #minna_de_swift by
みんなで Swift 復習会での談笑用スライド – 3rd #minna_de_swiftみんなで Swift 復習会での談笑用スライド – 3rd #minna_de_swift
みんなで Swift 復習会での談笑用スライド – 3rd #minna_de_swiftTomohiro Kumagai
439 views12 slides
Communities - Perl edition (RioJS) by
Communities - Perl edition (RioJS)Communities - Perl edition (RioJS)
Communities - Perl edition (RioJS)garux
774 views92 slides
全裸でワンライナー(仮) by
全裸でワンライナー(仮)全裸でワンライナー(仮)
全裸でワンライナー(仮)Yoshihiro Sugi
1.7K views99 slides
OSDC.TW - Gutscript for PHP haters by
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersLin Yo-An
2.4K views98 slides

What's hot(20)

Is Haskell an acceptable Perl? by osfameron
Is Haskell an acceptable Perl?Is Haskell an acceptable Perl?
Is Haskell an acceptable Perl?
osfameron1.6K views
Desenvolvimento web usando django by yurimalheiros
Desenvolvimento web usando djangoDesenvolvimento web usando django
Desenvolvimento web usando django
yurimalheiros1.3K views
みんなで Swift 復習会での談笑用スライド – 3rd #minna_de_swift by Tomohiro Kumagai
みんなで Swift 復習会での談笑用スライド – 3rd #minna_de_swiftみんなで Swift 復習会での談笑用スライド – 3rd #minna_de_swift
みんなで Swift 復習会での談笑用スライド – 3rd #minna_de_swift
Tomohiro Kumagai439 views
Communities - Perl edition (RioJS) by garux
Communities - Perl edition (RioJS)Communities - Perl edition (RioJS)
Communities - Perl edition (RioJS)
garux774 views
全裸でワンライナー(仮) by Yoshihiro Sugi
全裸でワンライナー(仮)全裸でワンライナー(仮)
全裸でワンライナー(仮)
Yoshihiro Sugi1.7K views
OSDC.TW - Gutscript for PHP haters by Lin Yo-An
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP haters
Lin Yo-An2.4K views
Mkscript sh by Ben Pope
Mkscript shMkscript sh
Mkscript sh
Ben Pope121 views
(Fun clojure) by Timo Sulg
(Fun clojure)(Fun clojure)
(Fun clojure)
Timo Sulg1.9K views
Redes sociais usando python by yurimalheiros
Redes sociais usando pythonRedes sociais usando python
Redes sociais usando python
yurimalheiros2.1K views
8時間耐久CakePHP2 勉強会 by Yusuke Ando
8時間耐久CakePHP2 勉強会8時間耐久CakePHP2 勉強会
8時間耐久CakePHP2 勉強会
Yusuke Ando16.5K views
An Elephant of a Different Colour: Hack by Vic Metcalfe
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: Hack
Vic Metcalfe2.1K views
Descobrindo a linguagem Perl by garux
Descobrindo a linguagem PerlDescobrindo a linguagem Perl
Descobrindo a linguagem Perl
garux868 views
Kotlin Programming Language. What it is all about. Roman Belov, PMM in Kotlin by JetBrains Russia
Kotlin Programming Language. What it is all about. Roman Belov, PMM in KotlinKotlin Programming Language. What it is all about. Roman Belov, PMM in Kotlin
Kotlin Programming Language. What it is all about. Roman Belov, PMM in Kotlin
JetBrains Russia140 views
Frege is a Haskell for the JVM by jwausle
Frege is a Haskell for the JVMFrege is a Haskell for the JVM
Frege is a Haskell for the JVM
jwausle200 views
Lightning talk: Go by Evolve
Lightning talk: GoLightning talk: Go
Lightning talk: Go
Evolve69 views
Climbing the Abstract Syntax Tree (Bulgaria PHP 2016) by James Titcumb
Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)
Climbing the Abstract Syntax Tree (Bulgaria PHP 2016)
James Titcumb542 views
The Perl6 Type System by abrummett
The Perl6 Type SystemThe Perl6 Type System
The Perl6 Type System
abrummett2.4K views
Wx::Perl::Smart by lichtkind
Wx::Perl::SmartWx::Perl::Smart
Wx::Perl::Smart
lichtkind766 views

Viewers also liked

H Y P O C R I T E Dr by
H Y P O C R I T E  DrH Y P O C R I T E  Dr
H Y P O C R I T E Drghanyog
170 views3 slides
A FRAMEWORK FOR EXTRACTING AND MODELING HIPAA PRIVACY RULES FOR HEALTHCARE AP... by
A FRAMEWORK FOR EXTRACTING AND MODELING HIPAA PRIVACY RULES FOR HEALTHCARE AP...A FRAMEWORK FOR EXTRACTING AND MODELING HIPAA PRIVACY RULES FOR HEALTHCARE AP...
A FRAMEWORK FOR EXTRACTING AND MODELING HIPAA PRIVACY RULES FOR HEALTHCARE AP...hiij
218 views10 slides
PGDIM NAAC by
PGDIM NAACPGDIM NAAC
PGDIM NAACKawal Gill
598 views21 slides
1282927519Leaflet-204 by
1282927519Leaflet-2041282927519Leaflet-204
1282927519Leaflet-204Obada Alsaqqa
68 views2 slides
Term project application of research in businesses-methods in business resear... by
Term project application of research in businesses-methods in business resear...Term project application of research in businesses-methods in business resear...
Term project application of research in businesses-methods in business resear...Muhammad Asif Khan Awan
236 views11 slides
Brochure 1 by
Brochure 1Brochure 1
Brochure 1urshari
127 views2 slides

Viewers also liked(11)

H Y P O C R I T E Dr by ghanyog
H Y P O C R I T E  DrH Y P O C R I T E  Dr
H Y P O C R I T E Dr
ghanyog170 views
A FRAMEWORK FOR EXTRACTING AND MODELING HIPAA PRIVACY RULES FOR HEALTHCARE AP... by hiij
A FRAMEWORK FOR EXTRACTING AND MODELING HIPAA PRIVACY RULES FOR HEALTHCARE AP...A FRAMEWORK FOR EXTRACTING AND MODELING HIPAA PRIVACY RULES FOR HEALTHCARE AP...
A FRAMEWORK FOR EXTRACTING AND MODELING HIPAA PRIVACY RULES FOR HEALTHCARE AP...
hiij218 views
Term project application of research in businesses-methods in business resear... by Muhammad Asif Khan Awan
Term project application of research in businesses-methods in business resear...Term project application of research in businesses-methods in business resear...
Term project application of research in businesses-methods in business resear...
Brochure 1 by urshari
Brochure 1Brochure 1
Brochure 1
urshari127 views
M A U N A ( S I L E N C E) & S U P E R L I V I N G D R S H R I N I W A S ... by ghanyog
M A U N A ( S I L E N C E) &  S U P E R L I V I N G   D R  S H R I N I W A S ...M A U N A ( S I L E N C E) &  S U P E R L I V I N G   D R  S H R I N I W A S ...
M A U N A ( S I L E N C E) & S U P E R L I V I N G D R S H R I N I W A S ...
ghanyog104 views
Term project application of research in businesses-methods in business resear... by Muhammad Asif Khan Awan
Term project application of research in businesses-methods in business resear...Term project application of research in businesses-methods in business resear...
Term project application of research in businesses-methods in business resear...
Hunger Presentation by Maryelle Data
Hunger PresentationHunger Presentation
Hunger Presentation
Maryelle Data25.1K views
RazorFish Client Summit - Levi’s presentation by vstuhlen
RazorFish Client Summit - Levi’s presentationRazorFish Client Summit - Levi’s presentation
RazorFish Client Summit - Levi’s presentation
vstuhlen2.6K views

Similar to Swift - Modern & Expressive, or Magical Unicorn?

Rediscovering JavaScript: The Language Behind The Libraries by
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The LibrariesSimon Willison
20.1K views80 slides
What's in a language? By Cheng Lou by
What's in a language? By Cheng Lou What's in a language? By Cheng Lou
What's in a language? By Cheng Lou React London 2017
286 views72 slides
F# delight by
F# delightF# delight
F# delightpriort
295 views46 slides
Scala in a Java 8 World by
Scala in a Java 8 WorldScala in a Java 8 World
Scala in a Java 8 WorldDaniel Blyth
146 views40 slides
Swift Study #7 by
Swift Study #7Swift Study #7
Swift Study #7chanju Jeon
1.7K views20 slides
No excuses, switch to kotlin by
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
586 views25 slides

Similar to Swift - Modern & Expressive, or Magical Unicorn?(20)

Rediscovering JavaScript: The Language Behind The Libraries by Simon Willison
Rediscovering JavaScript: The Language Behind The LibrariesRediscovering JavaScript: The Language Behind The Libraries
Rediscovering JavaScript: The Language Behind The Libraries
Simon Willison20.1K views
F# delight by priort
F# delightF# delight
F# delight
priort295 views
Scala in a Java 8 World by Daniel Blyth
Scala in a Java 8 WorldScala in a Java 8 World
Scala in a Java 8 World
Daniel Blyth146 views
Swift Study #7 by chanju Jeon
Swift Study #7Swift Study #7
Swift Study #7
chanju Jeon1.7K views
No excuses, switch to kotlin by Thijs Suijten
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
Thijs Suijten586 views
JavaScript - Like a Box of Chocolates by Robert Nyman
JavaScript - Like a Box of ChocolatesJavaScript - Like a Box of Chocolates
JavaScript - Like a Box of Chocolates
Robert Nyman8.1K views
No excuses, switch to kotlin by Thijs Suijten
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
Thijs Suijten300 views
かとうの Kotlin 講座 こってり版 by Yutaka Kato
かとうの Kotlin 講座 こってり版かとうの Kotlin 講座 こってり版
かとうの Kotlin 講座 こってり版
Yutaka Kato411 views
About java by Jay Xu
About javaAbout java
About java
Jay Xu636 views
Writing Apps the Google-y Way (Brisbane) by Pamela Fox
Writing Apps the Google-y Way (Brisbane)Writing Apps the Google-y Way (Brisbane)
Writing Apps the Google-y Way (Brisbane)
Pamela Fox1.9K views
Intro to Advanced JavaScript by ryanstout
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
ryanstout599 views
AST Transformations at JFokus by HamletDRC
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
HamletDRC945 views
2.1 Recap From Day One by retronym
2.1 Recap From Day One2.1 Recap From Day One
2.1 Recap From Day One
retronym495 views
CodeCamp Iasi 10 march 2012 - Practical Groovy by Codecamp Romania
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
Codecamp Romania585 views
What Swift can teach us all by Pablo Villar
What Swift can teach us allWhat Swift can teach us all
What Swift can teach us all
Pablo Villar400 views
import java.io.;import java.util.;public class Dictionary {p.pdf by maheshkumar12354
import java.io.;import java.util.;public class Dictionary {p.pdfimport java.io.;import java.util.;public class Dictionary {p.pdf
import java.io.;import java.util.;public class Dictionary {p.pdf

Recently uploaded

Unleash The Monkeys by
Unleash The MonkeysUnleash The Monkeys
Unleash The MonkeysJacob Duijzer
8 views28 slides
The Path to DevOps by
The Path to DevOpsThe Path to DevOps
The Path to DevOpsJohn Valentino
5 views6 slides
Introduction to Git Source Control by
Introduction to Git Source ControlIntroduction to Git Source Control
Introduction to Git Source ControlJohn Valentino
5 views18 slides
SAP FOR CONTRACT MANUFACTURING.pdf by
SAP FOR CONTRACT MANUFACTURING.pdfSAP FOR CONTRACT MANUFACTURING.pdf
SAP FOR CONTRACT MANUFACTURING.pdfVirendra Rai, PMP
13 views2 slides
Bootstrapping vs Venture Capital.pptx by
Bootstrapping vs Venture Capital.pptxBootstrapping vs Venture Capital.pptx
Bootstrapping vs Venture Capital.pptxZeljko Svedic
12 views17 slides
WebAssembly by
WebAssemblyWebAssembly
WebAssemblyJens Siebert
52 views18 slides

Recently uploaded(20)

Introduction to Git Source Control by John Valentino
Introduction to Git Source ControlIntroduction to Git Source Control
Introduction to Git Source Control
John Valentino5 views
Bootstrapping vs Venture Capital.pptx by Zeljko Svedic
Bootstrapping vs Venture Capital.pptxBootstrapping vs Venture Capital.pptx
Bootstrapping vs Venture Capital.pptx
Zeljko Svedic12 views
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra... by Marc Müller
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra....NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
Marc Müller41 views
Generic or specific? Making sensible software design decisions by Bert Jan Schrijver
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions
predicting-m3-devopsconMunich-2023.pptx by Tier1 app
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptx
Tier1 app7 views
Fleet Management Software in India by Fleetable
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India
Fleetable12 views
tecnologia18.docx by nosi6702
tecnologia18.docxtecnologia18.docx
tecnologia18.docx
nosi67025 views
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with... by sparkfabrik
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
sparkfabrik8 views
Sprint 226 by ManageIQ
Sprint 226Sprint 226
Sprint 226
ManageIQ8 views
Copilot Prompting Toolkit_All Resources.pdf by Riccardo Zamana
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdf
Riccardo Zamana11 views
Gen Apps on Google Cloud PaLM2 and Codey APIs in Action by Márton Kodok
Gen Apps on Google Cloud PaLM2 and Codey APIs in ActionGen Apps on Google Cloud PaLM2 and Codey APIs in Action
Gen Apps on Google Cloud PaLM2 and Codey APIs in Action
Márton Kodok11 views
Software evolution understanding: Automatic extraction of software identifier... by Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm15 views

Swift - Modern & Expressive, or Magical Unicorn?

Editor's Notes

  1. Let’s start off with a point of reference that we can use as a starting point
  2. This is a Unicorn - in case there was some confusion. The rest of this presentation is about Swift!
  3. This should look familiar to those ActionScript developers in the audience. Seriously though let’s just take a look at the anatomy of this line of code: It declares the property using the VAR keyword, and provides clear indication though TYPE ANNOTATION that it is expecting a STRING as a value. This is what we would all refer to as an example of a STRONGLY TYPED language
  4. This on the other hand will be familiar to all the JavaScript developers in the house. Note the lack of a TYPE ANNOTATION and a terminating semi-colon. The type of data this variable can store is INFERRED by the value that is assigned to it. This is what you would usually refer to as a DYNAMIC LANGUAGE as the variable will happily store whatever you provide it with, a STRING one moment, a NUMERIC VALUE the next.
  5. Now this may come as no surprise, but both of the preceding examples were in fact SWIFT. Swift uses TYPE INFERENCE to determine what a variables type is based on the initial value assigned to it. However, unlike JavaScript it is a STRONGLY TYPED language and through a process referred to as TYPE SAFETY it makes sure during development and compilation that you don’t try and assign a different data type to a previously declared variable. If you do you’ll get an exception! You can annotate your variables with a specific type at declaration (and include semi-colons if you wish), but they are not required.
  6. One other thing before we move on is the difference between LET and VAR. LET is the CONSTANT keyword, so any value assigned to this type of variable is fixed and cannot be changed at a later time.
  7. As with most languages SWIFT controls execution flow through the use of LOOPS & CONDITIONALS. However while they operate in a similar fashion to other LANGUAGES you may be familiar with, except that curly braces are mandatory while parentheses aren’t. Also be aware that unlike a lot of WEB LANGUAGES, you can create infinite loops. Loops available are FOR, FOR…IN, WHILE & DO…WHILE
  8. Here we have the FOR loops. I’m not going to deep dive in to these. They are solely here to provide a point of reference where SWIFT offers differing implementations. For example CURLY BRACES are MANDATORY. PARENTHESES are not.
  9. This is the equivalent of the previous FOR loop. In this case it is using the HALF RANGE (..<) to loop through the values 0-9. If you wanted the loop to include the value 10, use a full RANGE (…)
  10. The more modern FOR…IN loop. This is the best practice approach advocated by Apple for iterating over ARRAYS etc.
  11. The WHILE loop. Make sure to include the incrementation variable otherwise you can easily create an infinite loop!
  12. Classic DO…WHILE. Again just to re-enforce, CURLY BRACES are required, PARENTHESES are not
  13. Like LOOPS, CONDITIONALS require CURLY BRACES even if you are doing a single line evaluation. Conditionals include: IF…ELSE & SWITCH…CASE
  14. Another thing to note is that SWITCH CASE statements do not support FALL THROUGH and you have to supply a ‘CATCH ALL’ should none of the CASE STATEMENTS fulfil the condition. BREAK statements are optional and are inferred - hence the lack of FALL THROUGH
  15. If you do want to ‘emulate’ a FALL THROUGH and you value is an INT, then you can use a RANGE to achieve this as shown above.
  16. Optionals, or SOME & NONE…
  17. This is how most people feel on first encountering OPTIONALS…
  18. Here we have the declaration of an OPTIONAL INT. Note the shorthand (and preferred) way of declaring the optional - Int?. Don’t confuse Int? with Int. Optionals are a separate type of their own that contain the property type you assign. The second line illustrates the ‘long form’ approach to declaring Optionals - and thus re-enforces that they are their own type.
  19. As the second line type annotation implies, this is an implicitly unwrapped optional. That is on assignment it unwraps the optional and assigns the property value to the variable. Be aware this will error if the type cannot be converted - as shown in the next few slides.
  20. As toInt() is an optional, myInt will have a type of Int? and the value of nil as myString cannot be converted to a number
  21. This time myInt has the value of 3. Remember though this is still an Int? not an Int
  22. This assigns the value of 3 to the variable myInt, but it sets it’s inferred type to Int? not Int as you may assume
  23. Here we get an error as the OPTIONAL object hasn’t been force unwrapped and is still an Int? and not an Int
  24. Here we get an error as the OPTIONAL object hasn’t been force unwrapped
  25. To achieve this we just added an exclamation mark to the end of toInt()
  26. Now the value of myInt is not only 3, but is also an Int not an Int?
  27. Be careful doing this in this manner as you will get an error if you try and force unwrap an OPTIONAL and chain it at the same time - as nil doesn’t have an advancedBy() method - so throws an error.
  28. Here we get an error as the OPTIONAL object has been force unwrapped and it is a nil value
  29. A cleaner approach is to using CONDITIONAL UNWRAPPING of an optional (this slide also demonstrates the concept of chaining). Here the variable myInt is part of a conditional expression so if the resulting value is nil, the condition is then false and the ELSE is run. If the value isn’t nil, then it is TRUE and the first statement is run - setting the value of myOtherInt in this case. Note myInt is garbage collected after this condition finishes its execution
  30. By default parameter names do not get displayed when invoking a function. While this can be fine in most instances you may want to display the parameters so you can give another developer an indication of what each value represents.
  31. If you want to make it more explicit what the parameters are that are being called you can prefix them with a hash #. Then when invoking the function you have to include the parameter names
  32. When using CONVENIENCE NAMES for PARAMETERS you still have to use the actual parameter name within your function. Using the convenience name will throw an error.
  33. Tuples are simple objects that allow you to plass back multiple values from a Function / Method. By default they are 0 based
  34. Tuples, like Function parameters, can have name parameters. In which case they can be accessed by the parameter names instead.
  35. Instead of naming the TUPLE parameters you can just declare the names as variables - in this case constants - and do the assignment and initialisation all at once.
  36. If there are any parameters you don’t require place an underscore _ in the position of the item you don’t require and it will not be created or assigned in this manner.
  37. VARIADIC FUNCTIONS allow you to provide a simple parameter signature that allows an arbitrary amount of items of a certain type. Note the return of the RANGE
  38. Here we can pass a function around and assign it to another variable by declaring the receiving variable as having the same FUNCTION TYPE as the function that is passed to it. So in this example we declare our variable as taking 2 INT PARAMETERS and returning 1 INT PARAMETER.
  39. This slide is a lay-up showing a function being used as a parameter of the SORTED function - this will be replaced by a CLOSURE in the next slide…
  40. CLOSURES or function literals are common in a lot of languages, but SWIFT has a specific way to declare a CLOSURE as you can see here. CURLY BRACES, then the parameters and the return type (if required). The all important IN keyword and then the actual closure code. In this example it just sorts the array alphabetically.
  41. In-out parameters cannot have default values, and variadic parameters cannot be marked as inout. If you mark a parameter as inout, it cannot also be marked as var or let. An in-out parameter has a value that is passed in to the function, is modified by the function, and is passed back out of the function to replace the original value.
  42. Structs are created using the STRUCT keyword and can contain both properties and methods. Structs are useful when you need to create a complex data transfer object on an ad-hoc basis within your application. Do not confuse these with an OBJECT LITERAL. STRUCTS can be instantiated like CLASSES.
  43. While SWIFT does create an INITIALISER in the background, by default it only calls the SUPER CLASS if there is some form of INHERITANCE. To fix our class all we need to do is create an EXPLICIT INITIALIZER that assigns values to our properties on INSTANTIATION. Now we have another problem. In it’s current form a PERSON CLASS always has to have a value for FIRSTNAME & LASTNAME supplied on creation. We can resolve this in a few different ways.
  44. Firstly we could supply defaults for those values. Or…
  45. We can create a CONVENIENCE INITIALISER. These are as the name implies a way to set additional INITIALISERS that allow for increased configuration on INSTANTIATION.
  46. With a CLASS you also have access to a deinitializer - DEINIT. This is when you destroy the object, either manually by setting it to NIL or as part of ARC.
  47. Getters & Setters are computed values not stored values
  48. Inheritance works the same as other languages except when dealing with variables
  49. As JobDescription is a stored value we cannot override it in the Manager subclass. To achieve this though we can create a computed variable of the same name and set the value that way. Note we have to call back up to the SUPER version of the variable to actually store it.
  50. PROTOCOLS are what a lot of languages refer to an INTERFACES. These are contract files that tell a class what METHODS and / or PROPERTIES they need to implement to fulfil that contract
  51. EXTENSIONS allow you to ADD FUNCTIONALITY to a object that you may not have access to the source code. Think of this like adding properties and methods to a JavaScript object via the PROTOTYPE chain.
  52. Not that they are actual implementations and have ACCESS MODIFIERS where required
  53. GENERICS are the ability to create GENERIC FUNCTIONS & METHODS that allow for greater flexibility within your code without the necessity of REPETITION.
  54. These are a few of the GENERIC TYPES in SWIFT - some we have already seen
  55. Take this contrived example - these 3 functions are pretty much identical. However it would be more efficient if we could do the same thing with just one function. That’s where GENERICS come in.
  56. Not the use of the token identifier <T>. The only requirement is that the type annotation <T> be the same as the parameters that are passed in
  57. Try Catch Availability checking Error Types / Throws
  58. This is a big deal as it allows the potential for iOS developers (initially) to build end to end applications solely in SWIFT - similar to the JS -> Node.js approach.
  59. More info can be found here…