iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)

Jonathan Engelsma
Jonathan EngelsmaAssociate Professor
Swift: Beyond the Basics
Lecture 03
Jonathan R. Engelsma, Ph.D.
TOPICS
• Closures
• Tuples
• Optionals
• Objects
• enum
• struct
• class
• Protocols
CLOSURES
• Self contained blocks of functionality that can be passed
around and used in your code.
• Analogous to blocks in Objective-C and to lambdas in other
programming languages.
• Can capture and store references to constants/variables from
the scope in which they are defined. This is known as closing,
hence the term closure.
CLOSURES
• Closures take one of 3 forms:
• Global functions are closures that have a name and do not
capture any values.
• Nested functions are closures that have a name and capture
values from their enclosing functions.
• Closure expressions are unnamed closures written in
lightweight syntax that capture values from their surrounding
context.
CLOSURE EXPRESSIONS
• A way to write inline closures in brief focused syntax.
• Syntactical optimizations provided for writing closures without
loss of clarity of intent.
• parameter/retval type inferencing
• implicit returns from single-expression closures
• shorthand arg names
• trailing closure syntax
DEFINING A CLOSURE
{ (params) -> returnType in
statements
}
• enclosed in {}
• -> separates the params from the return type.
• code statements follow the keyword in
SIMPLE CLOSURE EXAMPLE
TRAILING CLOSURES
• If a closure is passed as last argument of a function, it an
appear outside of the ():
• If there are no params other than the closure itself we can get
rid of the parens:
TUPLES IN SWIFT
• a tuple is a lightweight custom ordered collection of multiple
values.
• Swift tuples do not have their analog construct in Objective-C!
• Example:
TUPLE USAGE
• What can we use tuples for?
• Assign multiple values simultaneously:
TUPLE USAGE
• What can we use tuples for?
• returning multiple return values from a function:
TUPLE USAGE
• What can we use tuples for?
• swap values in two variables:
ACCESSINGTUPLEVALS
• How can we access values in a tuple?
SWIFT MAGIC…
• Observe that tuple syntax looks like function parameter lists!
• Not an accident - you can pass a tuple to an argument as its
parameters!
OPTIONALS IN SWIFT
• You can think of an optional in
Swift as a box that potentially wraps
an object of any type.
• An optional might wrap an object,
or it might not!
Optional
CREATING AN OPTIONAL
• How we create an optional:
• Note that these two variables are not Strings! They are
Optionals.
• Assigning the wrapped type to an Optional variable causes it
to automatically get wrapped!
PASSING OPTIONALS
• Optionals can be passed to functions where expected:
• If we pass the wrapped type (e.g. String) it gets automagically
wrapped before passing.
PASSING OPTIONALS
• You CANNOT pass an optional type where the wrapped
type is expected!
• You MUST unwrap an optional before using it…
UNWRAPPING OPTIONALS
• One way to unwrap an Optional is with the forced unwrap
operator, a postfix ‘!’:
• The ! operator simply unwraps the optional and passes to the
function the string (in this case “Behaving nicely” to the
function.
UNWRAPPING OPTIONALS
• We cannot send a message to a wrapped object before it is
unwrapped!
• But this works fine:
IMPLICITLY UNWRAPPED
OPTIONALS
• Swift provides another way of using an Optional where the
wrapped type is expected: ImplicitlyUnwrappedOptional:
• In this situation, mightBeNice gets implicitly unwrapped by
Swift when we pass it to the function.
DOES OPTIONAL CONTAIN A
WRAPPEDVALUE?
• To test if an optional contains a wrapped value, you can
compare it to nil.
• To specify an Optional with no wrapped value, assign or pass
nil.
MORE OPTIONAL FACTOIDS
• Optionals get set to nil automatically.
• You cannot unwrap an Optional
containing nothing, e.g. an Optional that
equates to nil.
• Unwrapping an Optional that contains
no value will crash your program!
CONDITIONAL
UNWRAPPING
• Swift has syntax for conditionally unwrapping Optionals:
• This would be a problem:
• This would not be:
OPTIONAL COMPARISONS
• When Optionals are used in comparisons, the wrapped value
is used. If there is no wrapped value, the comparison is false.
WHY OPTIONALS?
• Provides the interchange of object values in the legacy
Objective-C frameworks.
• need a way to send / receive nil to / from Objective-C.
• All Objective-C objects are handled as Optionals in Swift.
• Still some flux in the Swift wrappers of the legacy Objective-C
frameworks!
OBJECT IN SWIFT
• Three Object Flavors in Swift
• enum
• struct
• class
OBJECTS
• Declared with keyword enum, struct, or class respectively:
• Can be declared anywhere in the file, within another object,
within a function.
• Scope is determined by where the declaration is made.
OBJECTS
• Object declarations can have:
• Initializers - also known as constructors in other languages.
• Properties - variables declared at top level of an object.
Can be associated with the object (instance) or class.
• Methods - functions declared at top level of an object. Can
be associated with the object (instance) or class.
ENUMS
• an object type whose instances represent distinct predefined
alternative values. e.g. a set of constants that serve as
alternatives.
ENUM FACTOIDS
• Enums can be typed to Int, String, etc.
• Enums can have initializers (init), methods, and properties.
• By default, Enums are implemented as Ints with default values
assigned (starting with 0).
• An enum is a value type, that is, if assigned to a variable or
passed to a function, a copy is sent.
ENUMS WITH FIXEDVALUES
• enums can be defined with fixed values:
STRUCTS
• an object type in Swift, but could be thought of as a knocked
down version of class. Sits in between enum and class in
terms of its capabilities.
STRUCT FACTOIDS
• Nearly all of Swift’s built-in object types are structs, Int, String,
Array, etc.
• structs can have initializers, properties, and methods!
• An enum is a value type, that is, if assigned to a variable or
passed to a function, a copy is sent.
CLASS
CLASS FACTOIDS
• A class is a reference type. That is, when assigned to a variable
or passed to a function the reference is assigned or passed. A
copy is not made!
• A class can inherit the properties/behavior of a parent class.
• A class instance is mutable in place. e.g., even if the reference
is constant, values of the instance’s properties can be changed
via the reference.
WORKING WITH CLASSES
DEMO!!
PROTOCOLS IN SWIFT
• A protocol provides the the ability to define similarities
between unrelated objects.
PROTOCOL FACTOIDS
• Swift protocols are equivalent to abstract methods in C++ or
interfaces in Java.
• A class can subclass another class and implement one or
more protocols, however, the parent class must always be
listed first after the ‘:’ in the class def, with the list of comma
separated protocol names following.
1 of 39

Recommended

iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 02) by
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 02) iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 02)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 02) Jonathan Engelsma
930 views31 slides
Swift, a quick overview by
Swift, a quick overviewSwift, a quick overview
Swift, a quick overviewJulian Król
1.4K views20 slides
Intro to Scala by
 Intro to Scala Intro to Scala
Intro to Scalamanaswinimysore
163 views30 slides
Beginning Java for .NET developers by
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developersAndrei Rinea
18.4K views24 slides
Break Free with Managed Functional Programming: An Introduction to F# by
Break Free with Managed Functional Programming: An Introduction to F#Break Free with Managed Functional Programming: An Introduction to F#
Break Free with Managed Functional Programming: An Introduction to F#Dave Fancher
1.9K views91 slides
Break Free with Managed Functional Programming: An Introduction to F# by
Break Free with Managed Functional Programming: An Introduction to F#Break Free with Managed Functional Programming: An Introduction to F#
Break Free with Managed Functional Programming: An Introduction to F#IndyMobileNetDev
405 views91 slides

More Related Content

What's hot

java token by
java tokenjava token
java tokenJadavsejal
3.1K views8 slides
2 BytesC++ course_2014_c6_ constructors and other tools by
2 BytesC++ course_2014_c6_ constructors and other tools2 BytesC++ course_2014_c6_ constructors and other tools
2 BytesC++ course_2014_c6_ constructors and other toolskinan keshkeh
172 views52 slides
Preparing for Scala 3 by
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3Martin Odersky
11.1K views48 slides
AngularConf2015 by
AngularConf2015AngularConf2015
AngularConf2015Alessandro Giorgetti
581 views42 slides
Diving Into Scala Cats - Semigroups and Monoids by
Diving Into Scala Cats - Semigroups and MonoidsDiving Into Scala Cats - Semigroups and Monoids
Diving Into Scala Cats - Semigroups and MonoidsKnoldus Inc.
101 views45 slides
Variables in Pharo5 by
Variables in Pharo5Variables in Pharo5
Variables in Pharo5Marcus Denker
2.4K views31 slides

What's hot(20)

java token by Jadavsejal
java tokenjava token
java token
Jadavsejal3.1K views
2 BytesC++ course_2014_c6_ constructors and other tools by kinan keshkeh
2 BytesC++ course_2014_c6_ constructors and other tools2 BytesC++ course_2014_c6_ constructors and other tools
2 BytesC++ course_2014_c6_ constructors and other tools
kinan keshkeh172 views
Diving Into Scala Cats - Semigroups and Monoids by Knoldus Inc.
Diving Into Scala Cats - Semigroups and MonoidsDiving Into Scala Cats - Semigroups and Monoids
Diving Into Scala Cats - Semigroups and Monoids
Knoldus Inc.101 views
Python's dynamic nature (rough slides, November 2004) by Kiran Jonnalagadda
Python's dynamic nature (rough slides, November 2004)Python's dynamic nature (rough slides, November 2004)
Python's dynamic nature (rough slides, November 2004)
Kiran Jonnalagadda1.1K views
CSP: Huh? And Components by Daniel Fagnan
CSP: Huh? And ComponentsCSP: Huh? And Components
CSP: Huh? And Components
Daniel Fagnan245 views
Introduction of lambda expression and predicate builder by LearningTech
Introduction of lambda expression and predicate builderIntroduction of lambda expression and predicate builder
Introduction of lambda expression and predicate builder
LearningTech1.7K views
iOS development using Swift - Swift Basics (1) by Ahmed Ali
iOS development using Swift - Swift Basics (1)iOS development using Swift - Swift Basics (1)
iOS development using Swift - Swift Basics (1)
Ahmed Ali942 views
iOS development using Swift - Swift Basics (2) by Ahmed Ali
iOS development using Swift - Swift Basics (2)iOS development using Swift - Swift Basics (2)
iOS development using Swift - Swift Basics (2)
Ahmed Ali1K views
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu by Srimanta Sahu
A-Brief-Introduction-To-JAVA8_By_Srimanta_SahuA-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
A-Brief-Introduction-To-JAVA8_By_Srimanta_Sahu
Srimanta Sahu75 views
New c sharp4_features_part_v by Nico Ludwig
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_v
Nico Ludwig255 views

Viewers also liked

Thinking in swift ppt by
Thinking in swift pptThinking in swift ppt
Thinking in swift pptKeith Moon
423 views34 slides
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and... by
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...Ahmed Ali
1.4K views25 slides
iOS (7) Workshop by
iOS (7) WorkshopiOS (7) Workshop
iOS (7) WorkshopFábio Bernardo
1.1K views47 slides
iOS NSAgora #3: Objective-C vs. Swift by
iOS NSAgora #3: Objective-C vs. SwiftiOS NSAgora #3: Objective-C vs. Swift
iOS NSAgora #3: Objective-C vs. SwiftAlex Cristea
1.4K views44 slides
Hello Swift Final 5/5 - Structures and Classes by
Hello Swift Final 5/5 - Structures and ClassesHello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesCody Yun
1.2K views46 slides
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 05) by
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 05)iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 05)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 05)Jonathan Engelsma
1.3K views31 slides

Viewers also liked(20)

Thinking in swift ppt by Keith Moon
Thinking in swift pptThinking in swift ppt
Thinking in swift ppt
Keith Moon423 views
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and... by Ahmed Ali
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
Ahmed Ali1.4K views
iOS NSAgora #3: Objective-C vs. Swift by Alex Cristea
iOS NSAgora #3: Objective-C vs. SwiftiOS NSAgora #3: Objective-C vs. Swift
iOS NSAgora #3: Objective-C vs. Swift
Alex Cristea1.4K views
Hello Swift Final 5/5 - Structures and Classes by Cody Yun
Hello Swift Final 5/5 - Structures and ClassesHello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and Classes
Cody Yun1.2K views
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 05) by Jonathan Engelsma
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 05)iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 05)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 05)
Jonathan Engelsma1.3K views
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04) by Jonathan Engelsma
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)
Jonathan Engelsma1.1K views
Modern Objective-C @ Pragma Night by Giuseppe Arici
Modern Objective-C @ Pragma NightModern Objective-C @ Pragma Night
Modern Objective-C @ Pragma Night
Giuseppe Arici3.6K views
Spring MVC to iOS and the REST by Roy Clarkson
Spring MVC to iOS and the RESTSpring MVC to iOS and the REST
Spring MVC to iOS and the REST
Roy Clarkson26.4K views
Denis Lebedev, Swift by Yandex
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
Yandex38.4K views
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS by Jinkyu Kim
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOSSoftware architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
Jinkyu Kim2.6K views
A swift introduction to Swift by Giordano Scalzo
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
Giordano Scalzo104.8K views
An Introduction into the design of business using business architecture by Craig Martin
An Introduction into the design of business using business architectureAn Introduction into the design of business using business architecture
An Introduction into the design of business using business architecture
Craig Martin51.4K views
Writing Your App Swiftly by Sommer Panage
Writing Your App SwiftlyWriting Your App Swiftly
Writing Your App Swiftly
Sommer Panage2.3K views

Similar to iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)

Introduction to Scala by
Introduction to ScalaIntroduction to Scala
Introduction to ScalaViyaan Jhiingade
440 views54 slides
Enumerations in java.pptx by
Enumerations in java.pptxEnumerations in java.pptx
Enumerations in java.pptxSrizan Pokrel
41 views43 slides
Swift Tutorial Part 2. The complete guide for Swift programming language by
Swift Tutorial Part 2. The complete guide for Swift programming languageSwift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming languageHossam Ghareeb
3.5K views43 slides
Python first day by
Python first dayPython first day
Python first dayfarkhand
53 views25 slides
Python first day by
Python first dayPython first day
Python first dayMARISSTELLA2
19 views25 slides
Apex code (Salesforce) by
Apex code (Salesforce)Apex code (Salesforce)
Apex code (Salesforce)Mohammed Safwat Abu Kwaik
2.4K views161 slides

Similar to iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03) (20)

Swift Tutorial Part 2. The complete guide for Swift programming language by Hossam Ghareeb
Swift Tutorial Part 2. The complete guide for Swift programming languageSwift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming language
Hossam Ghareeb3.5K views
Python first day by farkhand
Python first dayPython first day
Python first day
farkhand53 views
Getting started with scala cats by Knoldus Inc.
Getting started with scala catsGetting started with scala cats
Getting started with scala cats
Knoldus Inc.74 views
Scala, Play 2.0 & Cloud Foundry by Pray Desai
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
Pray Desai3.3K views
Introduction to Scala by Rahul Jain
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Rahul Jain4.6K views
Apple Swift API Design Guideline by Chihyang Li
Apple Swift API Design GuidelineApple Swift API Design Guideline
Apple Swift API Design Guideline
Chihyang Li335 views
Week 1: Getting Your Hands Dirty - Part 1 by Jamshid Hashimi
Week 1: Getting Your Hands Dirty - Part 1Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1
Jamshid Hashimi840 views
Learning from "Effective Scala" by Kazuhiro Sera
Learning from "Effective Scala"Learning from "Effective Scala"
Learning from "Effective Scala"
Kazuhiro Sera1.9K views
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language by Hossam Ghareeb
Swift Tutorial Part 1. The Complete Guide For Swift Programming LanguageSwift Tutorial Part 1. The Complete Guide For Swift Programming Language
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
Hossam Ghareeb7.1K views

More from Jonathan Engelsma

Knowing Your Bees: Becoming a Better Beekeeper by
Knowing Your Bees: Becoming a Better BeekeeperKnowing Your Bees: Becoming a Better Beekeeper
Knowing Your Bees: Becoming a Better BeekeeperJonathan Engelsma
519 views35 slides
BIP Hive Scale Program Overview by
BIP Hive Scale Program OverviewBIP Hive Scale Program Overview
BIP Hive Scale Program OverviewJonathan Engelsma
677 views10 slides
Selling Honey Online by
Selling Honey OnlineSelling Honey Online
Selling Honey OnlineJonathan Engelsma
2.9K views33 slides
Selling Honey at Farmers Markets, Expos, etc. by
Selling Honey at Farmers Markets, Expos, etc. Selling Honey at Farmers Markets, Expos, etc.
Selling Honey at Farmers Markets, Expos, etc. Jonathan Engelsma
1.3K views31 slides
Harvesting and Handling Honey for Hobby and Small Sideline Beekeepers by
Harvesting and Handling Honey for Hobby and Small Sideline BeekeepersHarvesting and Handling Honey for Hobby and Small Sideline Beekeepers
Harvesting and Handling Honey for Hobby and Small Sideline BeekeepersJonathan Engelsma
1.9K views34 slides
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7) by
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)Jonathan Engelsma
988 views36 slides

More from Jonathan Engelsma(13)

Knowing Your Bees: Becoming a Better Beekeeper by Jonathan Engelsma
Knowing Your Bees: Becoming a Better BeekeeperKnowing Your Bees: Becoming a Better Beekeeper
Knowing Your Bees: Becoming a Better Beekeeper
Jonathan Engelsma519 views
Selling Honey at Farmers Markets, Expos, etc. by Jonathan Engelsma
Selling Honey at Farmers Markets, Expos, etc. Selling Honey at Farmers Markets, Expos, etc.
Selling Honey at Farmers Markets, Expos, etc.
Jonathan Engelsma1.3K views
Harvesting and Handling Honey for Hobby and Small Sideline Beekeepers by Jonathan Engelsma
Harvesting and Handling Honey for Hobby and Small Sideline BeekeepersHarvesting and Handling Honey for Hobby and Small Sideline Beekeepers
Harvesting and Handling Honey for Hobby and Small Sideline Beekeepers
Jonathan Engelsma1.9K views
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7) by Jonathan Engelsma
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)
Jonathan Engelsma988 views
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 09) by Jonathan Engelsma
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 09)iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 09)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 09)
Jonathan Engelsma805 views
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 06) by Jonathan Engelsma
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 06)iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 06)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 06)
What Every IT Manager Should Know About Mobile Apps by Jonathan Engelsma
What Every IT Manager Should Know About Mobile AppsWhat Every IT Manager Should Know About Mobile Apps
What Every IT Manager Should Know About Mobile Apps
Jonathan Engelsma866 views
2013 Michigan Beekeepers Association Annual Spring Conference by Jonathan Engelsma
2013 Michigan Beekeepers Association Annual Spring Conference2013 Michigan Beekeepers Association Annual Spring Conference
2013 Michigan Beekeepers Association Annual Spring Conference
Jonathan Engelsma837 views
2012 Michigan Beekeepers Association Annual Spring Conference - Beekeepers On... by Jonathan Engelsma
2012 Michigan Beekeepers Association Annual Spring Conference - Beekeepers On...2012 Michigan Beekeepers Association Annual Spring Conference - Beekeepers On...
2012 Michigan Beekeepers Association Annual Spring Conference - Beekeepers On...
Jonathan Engelsma1.1K views

Recently uploaded

FOSSLight Community Day 2023-11-30 by
FOSSLight Community Day 2023-11-30FOSSLight Community Day 2023-11-30
FOSSLight Community Day 2023-11-30Shane Coughlan
5 views18 slides
HarshithAkkapelli_Presentation.pdf by
HarshithAkkapelli_Presentation.pdfHarshithAkkapelli_Presentation.pdf
HarshithAkkapelli_Presentation.pdfharshithakkapelli
12 views16 slides
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra... by
.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üller
41 views62 slides
Fleet Management Software in India by
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India Fleetable
12 views1 slide
SAP FOR TYRE INDUSTRY.pdf by
SAP FOR TYRE INDUSTRY.pdfSAP FOR TYRE INDUSTRY.pdf
SAP FOR TYRE INDUSTRY.pdfVirendra Rai, PMP
27 views3 slides
JioEngage_Presentation.pptx by
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptxadmin125455
6 views4 slides

Recently uploaded(20)

FOSSLight Community Day 2023-11-30 by Shane Coughlan
FOSSLight Community Day 2023-11-30FOSSLight Community Day 2023-11-30
FOSSLight Community Day 2023-11-30
Shane Coughlan5 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
Fleet Management Software in India by Fleetable
Fleet Management Software in India Fleet Management Software in India
Fleet Management Software in India
Fleetable12 views
JioEngage_Presentation.pptx by admin125455
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptx
admin1254556 views
tecnologia18.docx by nosi6702
tecnologia18.docxtecnologia18.docx
tecnologia18.docx
nosi67025 views
Myths and Facts About Hospice Care: Busting Common Misconceptions by Care Coordinations
Myths and Facts About Hospice Care: Busting Common MisconceptionsMyths and Facts About Hospice Care: Busting Common Misconceptions
Myths and Facts About Hospice Care: Busting Common Misconceptions
Navigating container technology for enhanced security by Niklas Saari by Metosin Oy
Navigating container technology for enhanced security by Niklas SaariNavigating container technology for enhanced security by Niklas Saari
Navigating container technology for enhanced security by Niklas Saari
Metosin Oy14 views
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P... by NimaTorabi2
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
NimaTorabi215 views
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by Donato Onofri
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Donato Onofri890 views
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
Airline Booking Software by SharmiMehta
Airline Booking SoftwareAirline Booking Software
Airline Booking Software
SharmiMehta6 views
360 graden fabriek by info33492
360 graden fabriek360 graden fabriek
360 graden fabriek
info33492138 views
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... by Lisi Hocke
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Lisi Hocke35 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

iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 03)

  • 1. Swift: Beyond the Basics Lecture 03 Jonathan R. Engelsma, Ph.D.
  • 2. TOPICS • Closures • Tuples • Optionals • Objects • enum • struct • class • Protocols
  • 3. CLOSURES • Self contained blocks of functionality that can be passed around and used in your code. • Analogous to blocks in Objective-C and to lambdas in other programming languages. • Can capture and store references to constants/variables from the scope in which they are defined. This is known as closing, hence the term closure.
  • 4. CLOSURES • Closures take one of 3 forms: • Global functions are closures that have a name and do not capture any values. • Nested functions are closures that have a name and capture values from their enclosing functions. • Closure expressions are unnamed closures written in lightweight syntax that capture values from their surrounding context.
  • 5. CLOSURE EXPRESSIONS • A way to write inline closures in brief focused syntax. • Syntactical optimizations provided for writing closures without loss of clarity of intent. • parameter/retval type inferencing • implicit returns from single-expression closures • shorthand arg names • trailing closure syntax
  • 6. DEFINING A CLOSURE { (params) -> returnType in statements } • enclosed in {} • -> separates the params from the return type. • code statements follow the keyword in
  • 8. TRAILING CLOSURES • If a closure is passed as last argument of a function, it an appear outside of the (): • If there are no params other than the closure itself we can get rid of the parens:
  • 9. TUPLES IN SWIFT • a tuple is a lightweight custom ordered collection of multiple values. • Swift tuples do not have their analog construct in Objective-C! • Example:
  • 10. TUPLE USAGE • What can we use tuples for? • Assign multiple values simultaneously:
  • 11. TUPLE USAGE • What can we use tuples for? • returning multiple return values from a function:
  • 12. TUPLE USAGE • What can we use tuples for? • swap values in two variables:
  • 13. ACCESSINGTUPLEVALS • How can we access values in a tuple?
  • 14. SWIFT MAGIC… • Observe that tuple syntax looks like function parameter lists! • Not an accident - you can pass a tuple to an argument as its parameters!
  • 15. OPTIONALS IN SWIFT • You can think of an optional in Swift as a box that potentially wraps an object of any type. • An optional might wrap an object, or it might not! Optional
  • 16. CREATING AN OPTIONAL • How we create an optional: • Note that these two variables are not Strings! They are Optionals. • Assigning the wrapped type to an Optional variable causes it to automatically get wrapped!
  • 17. PASSING OPTIONALS • Optionals can be passed to functions where expected: • If we pass the wrapped type (e.g. String) it gets automagically wrapped before passing.
  • 18. PASSING OPTIONALS • You CANNOT pass an optional type where the wrapped type is expected! • You MUST unwrap an optional before using it…
  • 19. UNWRAPPING OPTIONALS • One way to unwrap an Optional is with the forced unwrap operator, a postfix ‘!’: • The ! operator simply unwraps the optional and passes to the function the string (in this case “Behaving nicely” to the function.
  • 20. UNWRAPPING OPTIONALS • We cannot send a message to a wrapped object before it is unwrapped! • But this works fine:
  • 21. IMPLICITLY UNWRAPPED OPTIONALS • Swift provides another way of using an Optional where the wrapped type is expected: ImplicitlyUnwrappedOptional: • In this situation, mightBeNice gets implicitly unwrapped by Swift when we pass it to the function.
  • 22. DOES OPTIONAL CONTAIN A WRAPPEDVALUE? • To test if an optional contains a wrapped value, you can compare it to nil. • To specify an Optional with no wrapped value, assign or pass nil.
  • 23. MORE OPTIONAL FACTOIDS • Optionals get set to nil automatically. • You cannot unwrap an Optional containing nothing, e.g. an Optional that equates to nil. • Unwrapping an Optional that contains no value will crash your program!
  • 24. CONDITIONAL UNWRAPPING • Swift has syntax for conditionally unwrapping Optionals: • This would be a problem: • This would not be:
  • 25. OPTIONAL COMPARISONS • When Optionals are used in comparisons, the wrapped value is used. If there is no wrapped value, the comparison is false.
  • 26. WHY OPTIONALS? • Provides the interchange of object values in the legacy Objective-C frameworks. • need a way to send / receive nil to / from Objective-C. • All Objective-C objects are handled as Optionals in Swift. • Still some flux in the Swift wrappers of the legacy Objective-C frameworks!
  • 27. OBJECT IN SWIFT • Three Object Flavors in Swift • enum • struct • class
  • 28. OBJECTS • Declared with keyword enum, struct, or class respectively: • Can be declared anywhere in the file, within another object, within a function. • Scope is determined by where the declaration is made.
  • 29. OBJECTS • Object declarations can have: • Initializers - also known as constructors in other languages. • Properties - variables declared at top level of an object. Can be associated with the object (instance) or class. • Methods - functions declared at top level of an object. Can be associated with the object (instance) or class.
  • 30. ENUMS • an object type whose instances represent distinct predefined alternative values. e.g. a set of constants that serve as alternatives.
  • 31. ENUM FACTOIDS • Enums can be typed to Int, String, etc. • Enums can have initializers (init), methods, and properties. • By default, Enums are implemented as Ints with default values assigned (starting with 0). • An enum is a value type, that is, if assigned to a variable or passed to a function, a copy is sent.
  • 32. ENUMS WITH FIXEDVALUES • enums can be defined with fixed values:
  • 33. STRUCTS • an object type in Swift, but could be thought of as a knocked down version of class. Sits in between enum and class in terms of its capabilities.
  • 34. STRUCT FACTOIDS • Nearly all of Swift’s built-in object types are structs, Int, String, Array, etc. • structs can have initializers, properties, and methods! • An enum is a value type, that is, if assigned to a variable or passed to a function, a copy is sent.
  • 35. CLASS
  • 36. CLASS FACTOIDS • A class is a reference type. That is, when assigned to a variable or passed to a function the reference is assigned or passed. A copy is not made! • A class can inherit the properties/behavior of a parent class. • A class instance is mutable in place. e.g., even if the reference is constant, values of the instance’s properties can be changed via the reference.
  • 38. PROTOCOLS IN SWIFT • A protocol provides the the ability to define similarities between unrelated objects.
  • 39. PROTOCOL FACTOIDS • Swift protocols are equivalent to abstract methods in C++ or interfaces in Java. • A class can subclass another class and implement one or more protocols, however, the parent class must always be listed first after the ‘:’ in the class def, with the list of comma separated protocol names following.