SlideShare a Scribd company logo
var, let, & ?
Optionals & Flow control around them
Matt Faluotico
Matt Faluotico
● Midwest born and raised, Ohio State
● iOS Developer at Xero (accounting SaaS)
● Employee App
● 3 years of iOS
● Twitter: @mattfxyz
● Web: mattf.xyz
● Github: /mattfxyz
● Introductions
● Objects
● Var, Let,
● Optionals
● Unwrapping
● Implementing
● Dependency injection
● Conclusion
● Q&A
Hello!
Objects
Objects in Swift
Everything is an object!
● Swift is still strongly typed, even if it doesn't quite look like it
● Grew from C & Objective-C
● Even primitives (Int, String, Bool, etc...)
Compiler will assume the type
var str = "Hello, With The Best" // Assumed to be a String
var specificStr: String = "Hello (again), With The Best"
Both are Strings!
● Reassignable to other Strings
print(str.dynamicType) // => String
print(specificStr.dynamicType) // => String
● Because we used var
Objects in Swift
var vs. let
Keyword for declaring a mutable object
● If you’re going to reassign the object
● If you’re using structs
var str = "Hello, playground"
str = "A different playground"
● Compiler is okay with this
var
Keyword for declaring a constant object
● If you’re keep the same reference to an object
● Your struct is not changing
let str = "Hello, playground"
str = "A different playground" // Compiler error
● Structs behave differently than classes
● Mutability is more defined by changing the pointer
let
let for classes
class MyStruct {
var number: Int
var name: String
}
let c = MyClass(number: 0, name: "cat")
s.number = 12 // This is not mutating the class
● Changing the properties on the heap
● Structs live on the stack
○ Much faster
● But they have a constant size and are immutable
● When you reassign to a struct, you create an entire new object on the stack
struct MyStruct {
var number: Int
var name: String
}
let s = MyStruct(number: 0, name: "cat")
//s.number = 12
● For structs this fails
let for structs
Remember our string?
var specificStr: String = "Hello (again), With The Best"
var specificStr: String = nil
● This breaks the things...
Objects can’t be nil
So we have Optionals
● A traditional type must hold a value (cannot be nil)
● An optional wraps any type in a form that allows nil
“there is a value, and it equals x” – Swift Programming Language
● We use the ? to declare something as an optional
var str: String? = "Hello, With The Best"
Optionals
Why Optionals?
We know ahead of time if the object we're working with is capable of being nil and
we can handle it appropriately.
● Why check to see if something is nil if it cannot be nil?
● Let programmers consuming an API or library which parts are optional
● Xcode's compiler leads to less mistakes
● Objective-c compatibility: All pointers can be nil
We’ll always know if something could potentially be nil
● Force Unwrapping (!)
○ Returns the value, but the program will crash if nil is found
○ Using ! is called “unsafe” but still commonly used
○ For unwrapping causes a runtime error when the object is nil
var str: String? = "Hello, With The Best"
print(str!)
● Optional Chaining (?)
○ Returns the value IFF the value exists
○ Will only execute if the object can be unwrapped
■ Will return nil if it can’t be unwrapped
var str: String? = "Hello, With The Best"
var n: = str?.characters.count
Unwrapping Optionals
● Should always unwrap optionals
let x = str?.characters.first
let a = str?.stringByAppendingString("cat")
let start = str?.startIndex
let end = str?.endIndex
● All of those question marks look messy
● Everyone agrees
Unwrapping Optionals
● if-let is the solution
if let s = str {
let x = s.characters.first
let a = s.stringByAppendingString("cat")
let start = s.startIndex
let end = st.endIndex
}
● If we can unwrap the object, bind it to an immutable value
● Since they’re objects, all the changes affect both
Optional Binding
Option Binding
if let s = aString,
let i = s.characters.count,
let b = aBool,
let f = aFloat {
print(s)
print(i)
print(b)
print(f)
print("everything was unwrapped!")
} else ...
● You can even check for multiple unwraps in one if-let statement
● Use the previous unwrapped results in following conditions!
● As soon as one value is nil, the condition is false
○ Handle that one with an else case!
Left Hand Flow
● Left should always be good
● Ray Wenderlich says it best
“When coding with conditionals, the left hand margin of the code should be the
"golden" or "happy" path. That is, don't nest if statements. Multiple return statements
are OK”
● if-let puts the “happy” value on the left side, but it still requires nesting ifs
● Return early for readability
Left hand rule
Guard
● Check for a condition that must be true to continue in the scope
● If it’s true, continue
○ But… you must leave inside the else block
○ That new variable is also available for the rest of the scope
func makeRequest(sessionManager session: SessionManager?) {
guard sm = session else {
return
}
sm.something()
}
Implementation
Optionals are actually just Swift enums
enum Optional<T> : Reflectable, NilLiteralConvertible {
case None
case Some(T)
init()
init(_ some: T)
}
● Initialized with a value or with an object
● The None case is just nil
Implementation
● Because they’re optionals, there are some cool thing we can do with them
● A lower level version of if-let
○ Because if-let is just a shortcut
let someOptional: Int? = 42
if case Optional.Some(let x) = someOptional {
print(x)
}
if case let x? = someOptional {
print(x.dynamicType)
print(x)
}
Implementation
Only continue if the value can be unwrapped
for case let x? in a {
print(x)
}
You can check for conditions in loops
for var x in a where x > 34 {
print(x)
}
(this one still iterates over nil)
Same for for loops
Implicitly Unwrapped Optionals
& “Dependency Injection”
Master → Details
(most applications)
So you have a class...
class DetailViewController: UIViewController {
var username: String
var profilePicture: UIImage
...
}
● “Class __ has no initializers”
● All non-optionals must have values after initialization
● View Controllers don’t always fill all of their properties in initialization
You know that the value isn’t going to be nil when you want to use it…
The “Master” Controller is going to provide it
But you get an error
Let’s add optionals!
class DetailViewController: UIViewController {
var username: String?
var profilePicture: UIImage?
...
}
Not you have to unwrap for every use…
Nah
Let’s add optionals!
Implicitly Unwrapped Optionals
class DetailViewController: UIViewController {
var username: String?
var profilePicture: UIImage!
...
}
● In between a traditional object and an optional
● Most commonly used in multi-step-initialization
● “Compiler Magic”
“An implicitly unwrapped optional is a normal optional behind the scenes, but can
also be used like a non optional value”
● They’re dangers. Be careful out there
Implicitly Unwrapped Optionals
Summary
● Type safe Swift
● “Nil safe” from optionals
● Left is happy
● There’s a way around it

More Related Content

What's hot

Getting started with C# Programming
Getting started with C# ProgrammingGetting started with C# Programming
Getting started with C# Programming
Bhushan Mulmule
 
Java generics(Under The Hood Of The Compiler) by Harmeet singh
Java generics(Under The Hood Of The Compiler) by Harmeet singhJava generics(Under The Hood Of The Compiler) by Harmeet singh
Java generics(Under The Hood Of The Compiler) by Harmeet singh
Harmeet Singh(Taara)
 
JS Responsibilities
JS ResponsibilitiesJS Responsibilities
JS Responsibilities
Brendan Eich
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
Juan Medina
 
Dynamic Swift
Dynamic SwiftDynamic Swift
Dynamic Swift
Saul Mora
 
Smalltalk, the dynamic language
Smalltalk, the dynamic languageSmalltalk, the dynamic language
Smalltalk, the dynamic language
mohamedsamyali
 
Start with swift
Start with swiftStart with swift
Oslo.versioned objects - Deep Dive
Oslo.versioned objects - Deep DiveOslo.versioned objects - Deep Dive
Oslo.versioned objects - Deep Dive
davanum
 
Where to type_std_move?
Where to type_std_move?Where to type_std_move?
Where to type_std_move?
Andrey Upadyshev
 
Swift, a quick overview
Swift, a quick overviewSwift, a quick overview
Swift, a quick overview
Julian Król
 
Introduction to Smalltalk
Introduction to SmalltalkIntroduction to Smalltalk
Introduction to Smalltalk
kim.mens
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Raghavan Mohan
 
JavaScript: The Language
JavaScript: The LanguageJavaScript: The Language
JavaScript: The Language
Engage Software
 
Typescript Basics
Typescript BasicsTypescript Basics
Typescript Basics
Manikandan [M M K]
 
Getting started with typescript and angular 2
Getting started with typescript  and angular 2Getting started with typescript  and angular 2
Getting started with typescript and angular 2
Knoldus Inc.
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlin
Sergey Bandysik
 
Whats to come with swift generics
Whats to come with swift genericsWhats to come with swift generics
Whats to come with swift generics
Denis Poifol
 
Typescript
TypescriptTypescript
Typescript
Nikhil Thomas
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
Ilio Catallo
 
Software Developer Training
Software Developer TrainingSoftware Developer Training
Software Developer Training
rungwiroon komalittipong
 

What's hot (20)

Getting started with C# Programming
Getting started with C# ProgrammingGetting started with C# Programming
Getting started with C# Programming
 
Java generics(Under The Hood Of The Compiler) by Harmeet singh
Java generics(Under The Hood Of The Compiler) by Harmeet singhJava generics(Under The Hood Of The Compiler) by Harmeet singh
Java generics(Under The Hood Of The Compiler) by Harmeet singh
 
JS Responsibilities
JS ResponsibilitiesJS Responsibilities
JS Responsibilities
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
 
Dynamic Swift
Dynamic SwiftDynamic Swift
Dynamic Swift
 
Smalltalk, the dynamic language
Smalltalk, the dynamic languageSmalltalk, the dynamic language
Smalltalk, the dynamic language
 
Start with swift
Start with swiftStart with swift
Start with swift
 
Oslo.versioned objects - Deep Dive
Oslo.versioned objects - Deep DiveOslo.versioned objects - Deep Dive
Oslo.versioned objects - Deep Dive
 
Where to type_std_move?
Where to type_std_move?Where to type_std_move?
Where to type_std_move?
 
Swift, a quick overview
Swift, a quick overviewSwift, a quick overview
Swift, a quick overview
 
Introduction to Smalltalk
Introduction to SmalltalkIntroduction to Smalltalk
Introduction to Smalltalk
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
JavaScript: The Language
JavaScript: The LanguageJavaScript: The Language
JavaScript: The Language
 
Typescript Basics
Typescript BasicsTypescript Basics
Typescript Basics
 
Getting started with typescript and angular 2
Getting started with typescript  and angular 2Getting started with typescript  and angular 2
Getting started with typescript and angular 2
 
1 kotlin vs. java: some java issues addressed in kotlin
1  kotlin vs. java: some java issues addressed in kotlin1  kotlin vs. java: some java issues addressed in kotlin
1 kotlin vs. java: some java issues addressed in kotlin
 
Whats to come with swift generics
Whats to come with swift genericsWhats to come with swift generics
Whats to come with swift generics
 
Typescript
TypescriptTypescript
Typescript
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
 
Software Developer Training
Software Developer TrainingSoftware Developer Training
Software Developer Training
 

Similar to Optionals by Matt Faluotico

Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
Mukesh Kumar
 
pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdf
PuneetChaturvedi23
 
Dart workshop
Dart workshopDart workshop
Dart workshop
Vishnu Suresh
 
JavaScript blast
JavaScript blastJavaScript blast
JavaScript blastdominion
 
Clojure Small Intro
Clojure Small IntroClojure Small Intro
Clojure Small Intro
John Vlachoyiannis
 
7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin
Luca Guadagnini
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11
Åsa Pehrsson
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersSkills Matter
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
Martin Ockajak
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2Chris Farrell
 
Cat's anatomy
Cat's anatomyCat's anatomy
Cat's anatomy
Nicola Bonelli
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Kotlin
KotlinKotlin
Kotlin
BoKaiRuan
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
Jayaprakash R
 
Python to scala
Python to scalaPython to scala
Python to scala
kao kuo-tung
 
Quick python reference
Quick python referenceQuick python reference
Quick python referenceJayant Parida
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
Nehal Shah
 
Python Essentials - PICT.pdf
Python Essentials - PICT.pdfPython Essentials - PICT.pdf
Python Essentials - PICT.pdf
Prashant Jamkhande
 

Similar to Optionals by Matt Faluotico (20)

Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
pure-functional-programming.pdf
pure-functional-programming.pdfpure-functional-programming.pdf
pure-functional-programming.pdf
 
Dart workshop
Dart workshopDart workshop
Dart workshop
 
JavaScript blast
JavaScript blastJavaScript blast
JavaScript blast
 
Clojure Small Intro
Clojure Small IntroClojure Small Intro
Clojure Small Intro
 
7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
 
Cat's anatomy
Cat's anatomyCat's anatomy
Cat's anatomy
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Kotlin
KotlinKotlin
Kotlin
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
Python to scala
Python to scalaPython to scala
Python to scala
 
Quick python reference
Quick python referenceQuick python reference
Quick python reference
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
 
Python Essentials - PICT.pdf
Python Essentials - PICT.pdfPython Essentials - PICT.pdf
Python Essentials - PICT.pdf
 

More from WithTheBest

Riccardo Vittoria
Riccardo VittoriaRiccardo Vittoria
Riccardo Vittoria
WithTheBest
 
Recreating history in virtual reality
Recreating history in virtual realityRecreating history in virtual reality
Recreating history in virtual reality
WithTheBest
 
Engaging and sharing your VR experience
Engaging and sharing your VR experienceEngaging and sharing your VR experience
Engaging and sharing your VR experience
WithTheBest
 
How to survive the early days of VR as an Indie Studio
How to survive the early days of VR as an Indie StudioHow to survive the early days of VR as an Indie Studio
How to survive the early days of VR as an Indie Studio
WithTheBest
 
Mixed reality 101
Mixed reality 101 Mixed reality 101
Mixed reality 101
WithTheBest
 
Unlocking Human Potential with Immersive Technology
Unlocking Human Potential with Immersive TechnologyUnlocking Human Potential with Immersive Technology
Unlocking Human Potential with Immersive Technology
WithTheBest
 
Building your own video devices
Building your own video devicesBuilding your own video devices
Building your own video devices
WithTheBest
 
Maximizing performance of 3 d user generated assets in unity
Maximizing performance of 3 d user generated assets in unityMaximizing performance of 3 d user generated assets in unity
Maximizing performance of 3 d user generated assets in unity
WithTheBest
 
Wizdish rovr
Wizdish rovrWizdish rovr
Wizdish rovr
WithTheBest
 
Haptics & amp; null space vr
Haptics & amp; null space vrHaptics & amp; null space vr
Haptics & amp; null space vr
WithTheBest
 
How we use vr to break the laws of physics
How we use vr to break the laws of physicsHow we use vr to break the laws of physics
How we use vr to break the laws of physics
WithTheBest
 
The Virtual Self
The Virtual Self The Virtual Self
The Virtual Self
WithTheBest
 
You dont have to be mad to do VR and AR ... but it helps
You dont have to be mad to do VR and AR ... but it helpsYou dont have to be mad to do VR and AR ... but it helps
You dont have to be mad to do VR and AR ... but it helps
WithTheBest
 
Omnivirt overview
Omnivirt overviewOmnivirt overview
Omnivirt overview
WithTheBest
 
VR Interactions - Jason Jerald
VR Interactions - Jason JeraldVR Interactions - Jason Jerald
VR Interactions - Jason Jerald
WithTheBest
 
Japheth Funding your startup - dating the devil
Japheth  Funding your startup - dating the devilJapheth  Funding your startup - dating the devil
Japheth Funding your startup - dating the devil
WithTheBest
 
Transported vr the virtual reality platform for real estate
Transported vr the virtual reality platform for real estateTransported vr the virtual reality platform for real estate
Transported vr the virtual reality platform for real estate
WithTheBest
 
Measuring Behavior in VR - Rob Merki Cognitive VR
Measuring Behavior in VR - Rob Merki Cognitive VRMeasuring Behavior in VR - Rob Merki Cognitive VR
Measuring Behavior in VR - Rob Merki Cognitive VR
WithTheBest
 
Global demand for Mixed Realty (VR/AR) content is about to explode.
Global demand for Mixed Realty (VR/AR) content is about to explode. Global demand for Mixed Realty (VR/AR) content is about to explode.
Global demand for Mixed Realty (VR/AR) content is about to explode.
WithTheBest
 
VR, a new technology over 40,000 years old
VR, a new technology over 40,000 years oldVR, a new technology over 40,000 years old
VR, a new technology over 40,000 years old
WithTheBest
 

More from WithTheBest (20)

Riccardo Vittoria
Riccardo VittoriaRiccardo Vittoria
Riccardo Vittoria
 
Recreating history in virtual reality
Recreating history in virtual realityRecreating history in virtual reality
Recreating history in virtual reality
 
Engaging and sharing your VR experience
Engaging and sharing your VR experienceEngaging and sharing your VR experience
Engaging and sharing your VR experience
 
How to survive the early days of VR as an Indie Studio
How to survive the early days of VR as an Indie StudioHow to survive the early days of VR as an Indie Studio
How to survive the early days of VR as an Indie Studio
 
Mixed reality 101
Mixed reality 101 Mixed reality 101
Mixed reality 101
 
Unlocking Human Potential with Immersive Technology
Unlocking Human Potential with Immersive TechnologyUnlocking Human Potential with Immersive Technology
Unlocking Human Potential with Immersive Technology
 
Building your own video devices
Building your own video devicesBuilding your own video devices
Building your own video devices
 
Maximizing performance of 3 d user generated assets in unity
Maximizing performance of 3 d user generated assets in unityMaximizing performance of 3 d user generated assets in unity
Maximizing performance of 3 d user generated assets in unity
 
Wizdish rovr
Wizdish rovrWizdish rovr
Wizdish rovr
 
Haptics & amp; null space vr
Haptics & amp; null space vrHaptics & amp; null space vr
Haptics & amp; null space vr
 
How we use vr to break the laws of physics
How we use vr to break the laws of physicsHow we use vr to break the laws of physics
How we use vr to break the laws of physics
 
The Virtual Self
The Virtual Self The Virtual Self
The Virtual Self
 
You dont have to be mad to do VR and AR ... but it helps
You dont have to be mad to do VR and AR ... but it helpsYou dont have to be mad to do VR and AR ... but it helps
You dont have to be mad to do VR and AR ... but it helps
 
Omnivirt overview
Omnivirt overviewOmnivirt overview
Omnivirt overview
 
VR Interactions - Jason Jerald
VR Interactions - Jason JeraldVR Interactions - Jason Jerald
VR Interactions - Jason Jerald
 
Japheth Funding your startup - dating the devil
Japheth  Funding your startup - dating the devilJapheth  Funding your startup - dating the devil
Japheth Funding your startup - dating the devil
 
Transported vr the virtual reality platform for real estate
Transported vr the virtual reality platform for real estateTransported vr the virtual reality platform for real estate
Transported vr the virtual reality platform for real estate
 
Measuring Behavior in VR - Rob Merki Cognitive VR
Measuring Behavior in VR - Rob Merki Cognitive VRMeasuring Behavior in VR - Rob Merki Cognitive VR
Measuring Behavior in VR - Rob Merki Cognitive VR
 
Global demand for Mixed Realty (VR/AR) content is about to explode.
Global demand for Mixed Realty (VR/AR) content is about to explode. Global demand for Mixed Realty (VR/AR) content is about to explode.
Global demand for Mixed Realty (VR/AR) content is about to explode.
 
VR, a new technology over 40,000 years old
VR, a new technology over 40,000 years oldVR, a new technology over 40,000 years old
VR, a new technology over 40,000 years old
 

Recently uploaded

Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Zilliz
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 

Recently uploaded (20)

Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...Building RAG with self-deployed Milvus vector database and Snowpark Container...
Building RAG with self-deployed Milvus vector database and Snowpark Container...
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 

Optionals by Matt Faluotico

  • 1. var, let, & ? Optionals & Flow control around them Matt Faluotico
  • 2. Matt Faluotico ● Midwest born and raised, Ohio State ● iOS Developer at Xero (accounting SaaS) ● Employee App ● 3 years of iOS ● Twitter: @mattfxyz ● Web: mattf.xyz ● Github: /mattfxyz
  • 3. ● Introductions ● Objects ● Var, Let, ● Optionals ● Unwrapping ● Implementing ● Dependency injection ● Conclusion ● Q&A Hello!
  • 5. Objects in Swift Everything is an object! ● Swift is still strongly typed, even if it doesn't quite look like it ● Grew from C & Objective-C ● Even primitives (Int, String, Bool, etc...) Compiler will assume the type var str = "Hello, With The Best" // Assumed to be a String var specificStr: String = "Hello (again), With The Best" Both are Strings!
  • 6. ● Reassignable to other Strings print(str.dynamicType) // => String print(specificStr.dynamicType) // => String ● Because we used var Objects in Swift
  • 8. Keyword for declaring a mutable object ● If you’re going to reassign the object ● If you’re using structs var str = "Hello, playground" str = "A different playground" ● Compiler is okay with this var
  • 9. Keyword for declaring a constant object ● If you’re keep the same reference to an object ● Your struct is not changing let str = "Hello, playground" str = "A different playground" // Compiler error ● Structs behave differently than classes ● Mutability is more defined by changing the pointer let
  • 10. let for classes class MyStruct { var number: Int var name: String } let c = MyClass(number: 0, name: "cat") s.number = 12 // This is not mutating the class ● Changing the properties on the heap
  • 11. ● Structs live on the stack ○ Much faster ● But they have a constant size and are immutable ● When you reassign to a struct, you create an entire new object on the stack struct MyStruct { var number: Int var name: String } let s = MyStruct(number: 0, name: "cat") //s.number = 12 ● For structs this fails let for structs
  • 12. Remember our string? var specificStr: String = "Hello (again), With The Best" var specificStr: String = nil ● This breaks the things... Objects can’t be nil
  • 13. So we have Optionals
  • 14. ● A traditional type must hold a value (cannot be nil) ● An optional wraps any type in a form that allows nil “there is a value, and it equals x” – Swift Programming Language ● We use the ? to declare something as an optional var str: String? = "Hello, With The Best" Optionals
  • 15. Why Optionals? We know ahead of time if the object we're working with is capable of being nil and we can handle it appropriately. ● Why check to see if something is nil if it cannot be nil? ● Let programmers consuming an API or library which parts are optional ● Xcode's compiler leads to less mistakes ● Objective-c compatibility: All pointers can be nil We’ll always know if something could potentially be nil
  • 16. ● Force Unwrapping (!) ○ Returns the value, but the program will crash if nil is found ○ Using ! is called “unsafe” but still commonly used ○ For unwrapping causes a runtime error when the object is nil var str: String? = "Hello, With The Best" print(str!) ● Optional Chaining (?) ○ Returns the value IFF the value exists ○ Will only execute if the object can be unwrapped ■ Will return nil if it can’t be unwrapped var str: String? = "Hello, With The Best" var n: = str?.characters.count Unwrapping Optionals
  • 17. ● Should always unwrap optionals let x = str?.characters.first let a = str?.stringByAppendingString("cat") let start = str?.startIndex let end = str?.endIndex ● All of those question marks look messy ● Everyone agrees Unwrapping Optionals
  • 18. ● if-let is the solution if let s = str { let x = s.characters.first let a = s.stringByAppendingString("cat") let start = s.startIndex let end = st.endIndex } ● If we can unwrap the object, bind it to an immutable value ● Since they’re objects, all the changes affect both Optional Binding
  • 19. Option Binding if let s = aString, let i = s.characters.count, let b = aBool, let f = aFloat { print(s) print(i) print(b) print(f) print("everything was unwrapped!") } else ... ● You can even check for multiple unwraps in one if-let statement ● Use the previous unwrapped results in following conditions! ● As soon as one value is nil, the condition is false ○ Handle that one with an else case!
  • 21. ● Left should always be good ● Ray Wenderlich says it best “When coding with conditionals, the left hand margin of the code should be the "golden" or "happy" path. That is, don't nest if statements. Multiple return statements are OK” ● if-let puts the “happy” value on the left side, but it still requires nesting ifs ● Return early for readability Left hand rule
  • 22. Guard ● Check for a condition that must be true to continue in the scope ● If it’s true, continue ○ But… you must leave inside the else block ○ That new variable is also available for the rest of the scope func makeRequest(sessionManager session: SessionManager?) { guard sm = session else { return } sm.something() }
  • 24. Optionals are actually just Swift enums enum Optional<T> : Reflectable, NilLiteralConvertible { case None case Some(T) init() init(_ some: T) } ● Initialized with a value or with an object ● The None case is just nil Implementation
  • 25. ● Because they’re optionals, there are some cool thing we can do with them ● A lower level version of if-let ○ Because if-let is just a shortcut let someOptional: Int? = 42 if case Optional.Some(let x) = someOptional { print(x) } if case let x? = someOptional { print(x.dynamicType) print(x) } Implementation
  • 26. Only continue if the value can be unwrapped for case let x? in a { print(x) } You can check for conditions in loops for var x in a where x > 34 { print(x) } (this one still iterates over nil) Same for for loops
  • 27. Implicitly Unwrapped Optionals & “Dependency Injection”
  • 28. Master → Details (most applications)
  • 29. So you have a class... class DetailViewController: UIViewController { var username: String var profilePicture: UIImage ... }
  • 30. ● “Class __ has no initializers” ● All non-optionals must have values after initialization ● View Controllers don’t always fill all of their properties in initialization You know that the value isn’t going to be nil when you want to use it… The “Master” Controller is going to provide it But you get an error
  • 31. Let’s add optionals! class DetailViewController: UIViewController { var username: String? var profilePicture: UIImage? ... }
  • 32. Not you have to unwrap for every use… Nah Let’s add optionals!
  • 33. Implicitly Unwrapped Optionals class DetailViewController: UIViewController { var username: String? var profilePicture: UIImage! ... }
  • 34. ● In between a traditional object and an optional ● Most commonly used in multi-step-initialization ● “Compiler Magic” “An implicitly unwrapped optional is a normal optional behind the scenes, but can also be used like a non optional value” ● They’re dangers. Be careful out there Implicitly Unwrapped Optionals
  • 35. Summary ● Type safe Swift ● “Nil safe” from optionals ● Left is happy ● There’s a way around it