SlideShare una empresa de Scribd logo
1 de 39
Descargar para leer sin conexión
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.

Más contenido relacionado

La actualidad más candente

2 BytesC++ course_2014_c6_ constructors and other tools
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
 
Diving Into Scala Cats - Semigroups and Monoids
Diving Into Scala Cats - Semigroups and MonoidsDiving Into Scala Cats - Semigroups and Monoids
Diving Into Scala Cats - Semigroups and MonoidsKnoldus Inc.
 
Python's dynamic nature (rough slides, November 2004)
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 Jonnalagadda
 
CSP: Huh? And Components
CSP: Huh? And ComponentsCSP: Huh? And Components
CSP: Huh? And ComponentsDaniel Fagnan
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave ImplicitMartin Odersky
 
Introduction of lambda expression and predicate builder
Introduction of lambda expression and predicate builderIntroduction of lambda expression and predicate builder
Introduction of lambda expression and predicate builderLearningTech
 
iOS development using Swift - Swift Basics (1)
iOS development using Swift - Swift Basics (1)iOS development using Swift - Swift Basics (1)
iOS development using Swift - Swift Basics (1)Ahmed Ali
 
iOS development using Swift - Swift Basics (2)
iOS development using Swift - Swift Basics (2)iOS development using Swift - Swift Basics (2)
iOS development using Swift - Swift Basics (2)Ahmed Ali
 
A-Brief-Introduction-To-JAVA8_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_SahuSrimanta Sahu
 
New c sharp4_features_part_v
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_vNico Ludwig
 

La actualidad más candente (20)

java token
java tokenjava token
java token
 
2 BytesC++ course_2014_c6_ constructors and other tools
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
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
 
AngularConf2015
AngularConf2015AngularConf2015
AngularConf2015
 
Diving Into Scala Cats - Semigroups and Monoids
Diving Into Scala Cats - Semigroups and MonoidsDiving Into Scala Cats - Semigroups and Monoids
Diving Into Scala Cats - Semigroups and Monoids
 
Variables in Pharo5
Variables in Pharo5Variables in Pharo5
Variables in Pharo5
 
Java tokens
Java tokensJava tokens
Java tokens
 
Python's dynamic nature (rough slides, November 2004)
Python's dynamic nature (rough slides, November 2004)Python's dynamic nature (rough slides, November 2004)
Python's dynamic nature (rough slides, November 2004)
 
CSP: Huh? And Components
CSP: Huh? And ComponentsCSP: Huh? And Components
CSP: Huh? And Components
 
What To Leave Implicit
What To Leave ImplicitWhat To Leave Implicit
What To Leave Implicit
 
Introduction of lambda expression and predicate builder
Introduction of lambda expression and predicate builderIntroduction of lambda expression and predicate builder
Introduction of lambda expression and predicate builder
 
Swift
SwiftSwift
Swift
 
Java strings
Java stringsJava strings
Java strings
 
iOS development using Swift - Swift Basics (1)
iOS development using Swift - Swift Basics (1)iOS development using Swift - Swift Basics (1)
iOS development using Swift - Swift Basics (1)
 
Lambdas
LambdasLambdas
Lambdas
 
Learning typescript
Learning typescriptLearning typescript
Learning typescript
 
Introducing TypeScript
Introducing TypeScriptIntroducing TypeScript
Introducing TypeScript
 
iOS development using Swift - Swift Basics (2)
iOS development using Swift - Swift Basics (2)iOS development using Swift - Swift Basics (2)
iOS development using Swift - Swift Basics (2)
 
A-Brief-Introduction-To-JAVA8_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
 
New c sharp4_features_part_v
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_v
 

Destacado

Thinking in swift ppt
Thinking in swift pptThinking in swift ppt
Thinking in swift pptKeith Moon
 
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...
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...Ahmed Ali
 
iOS NSAgora #3: Objective-C vs. Swift
iOS NSAgora #3: Objective-C vs. SwiftiOS NSAgora #3: Objective-C vs. Swift
iOS NSAgora #3: Objective-C vs. SwiftAlex Cristea
 
Hello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesHello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesCody Yun
 
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)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 05)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)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)Jonathan Engelsma
 
Modern Objective-C @ Pragma Night
Modern Objective-C @ Pragma NightModern Objective-C @ Pragma Night
Modern Objective-C @ Pragma NightGiuseppe Arici
 
Spring MVC to iOS and the REST
Spring MVC to iOS and the RESTSpring MVC to iOS and the REST
Spring MVC to iOS and the RESTRoy Clarkson
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Workhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftWorkhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftVisual Engineering
 
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
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 iOSJinkyu Kim
 
Workshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresWorkshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresVisual Engineering
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
An Introduction into the design of business using business architecture
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 architectureCraig Martin
 
Writing Your App Swiftly
Writing Your App SwiftlyWriting Your App Swiftly
Writing Your App SwiftlySommer Panage
 

Destacado (20)

Thinking in swift ppt
Thinking in swift pptThinking in swift ppt
Thinking in swift ppt
 
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...
iOS Development using Swift: Enums, ARC, Delegation, Closures, Table View and...
 
iOS (7) Workshop
iOS (7) WorkshopiOS (7) Workshop
iOS (7) Workshop
 
iOS NSAgora #3: Objective-C vs. Swift
iOS NSAgora #3: Objective-C vs. SwiftiOS NSAgora #3: Objective-C vs. Swift
iOS NSAgora #3: Objective-C vs. Swift
 
Hello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and ClassesHello Swift Final 5/5 - Structures and Classes
Hello Swift Final 5/5 - Structures and Classes
 
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)
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 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)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 04)
 
Swift vs Objective-C
Swift vs Objective-CSwift vs Objective-C
Swift vs Objective-C
 
Modern Objective-C @ Pragma Night
Modern Objective-C @ Pragma NightModern Objective-C @ Pragma Night
Modern Objective-C @ Pragma Night
 
Ios - Intorduction to view controller
Ios - Intorduction to view controllerIos - Intorduction to view controller
Ios - Intorduction to view controller
 
iOS: Table Views
iOS: Table ViewsiOS: Table Views
iOS: Table Views
 
Spring MVC to iOS and the REST
Spring MVC to iOS and the RESTSpring MVC to iOS and the REST
Spring MVC to iOS and the REST
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Workhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftWorkhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de Swift
 
Software architectural design patterns(MVC, MVP, MVVM, VIPER) for iOS
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
 
Workshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresWorkshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - Structures
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Apple iOS
Apple iOSApple iOS
Apple iOS
 
An Introduction into the design of business using business architecture
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
 
Writing Your App Swiftly
Writing Your App SwiftlyWriting Your App Swiftly
Writing Your App Swiftly
 

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

Enumerations in java.pptx
Enumerations in java.pptxEnumerations in java.pptx
Enumerations in java.pptxSrizan Pokrel
 
Swift Tutorial Part 2. The complete guide for Swift programming language
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
 
Computer Sience, This is my presentation for beginners coding in python
Computer Sience, This is my presentation for beginners coding in pythonComputer Sience, This is my presentation for beginners coding in python
Computer Sience, This is my presentation for beginners coding in pythonalin173596
 
Python first day
Python first dayPython first day
Python first dayfarkhand
 
Getting started with scala cats
Getting started with scala catsGetting started with scala cats
Getting started with scala catsKnoldus Inc.
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryPray Desai
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaRahul Jain
 
Apple Swift API Design Guideline
Apple Swift API Design GuidelineApple Swift API Design Guideline
Apple Swift API Design GuidelineChihyang Li
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itlokeshpappaka10
 
Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Jamshid Hashimi
 
Learning from "Effective Scala"
Learning from "Effective Scala"Learning from "Effective Scala"
Learning from "Effective Scala"Kazuhiro Sera
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
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 LanguageHossam Ghareeb
 

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

Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Enumerations in java.pptx
Enumerations in java.pptxEnumerations in java.pptx
Enumerations in java.pptx
 
Swift Tutorial Part 2. The complete guide for Swift programming language
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
 
Computer Sience, This is my presentation for beginners coding in python
Computer Sience, This is my presentation for beginners coding in pythonComputer Sience, This is my presentation for beginners coding in python
Computer Sience, This is my presentation for beginners coding in python
 
Python first day
Python first dayPython first day
Python first day
 
Python first day
Python first dayPython first day
Python first day
 
Apex code (Salesforce)
Apex code (Salesforce)Apex code (Salesforce)
Apex code (Salesforce)
 
Java
JavaJava
Java
 
Getting started with scala cats
Getting started with scala catsGetting started with scala cats
Getting started with scala cats
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
Typescript
TypescriptTypescript
Typescript
 
Java
JavaJava
Java
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Apple Swift API Design Guideline
Apple Swift API Design GuidelineApple Swift API Design Guideline
Apple Swift API Design Guideline
 
Complete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept itComplete PPT about the Java lokesh kept it
Complete PPT about the Java lokesh kept it
 
Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1Week 1: Getting Your Hands Dirty - Part 1
Week 1: Getting Your Hands Dirty - Part 1
 
Learning from "Effective Scala"
Learning from "Effective Scala"Learning from "Effective Scala"
Learning from "Effective Scala"
 
Swift Tutorial Part 1. The Complete Guide For Swift Programming Language
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
 
Metaprogramming ruby
Metaprogramming rubyMetaprogramming ruby
Metaprogramming ruby
 
Subprogram
SubprogramSubprogram
Subprogram
 

Más de Jonathan Engelsma

Knowing Your Bees: Becoming a Better Beekeeper
Knowing Your Bees: Becoming a Better BeekeeperKnowing Your Bees: Becoming a Better Beekeeper
Knowing Your Bees: Becoming a Better BeekeeperJonathan Engelsma
 
BIP Hive Scale Program Overview
BIP Hive Scale Program OverviewBIP Hive Scale Program Overview
BIP Hive Scale Program OverviewJonathan Engelsma
 
Selling Honey at Farmers Markets, Expos, etc.
Selling Honey at Farmers Markets, Expos, etc. Selling Honey at Farmers Markets, Expos, etc.
Selling Honey at Farmers Markets, Expos, etc. Jonathan Engelsma
 
Harvesting and Handling Honey for Hobby and Small Sideline Beekeepers
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
 
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)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 7)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)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 09)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)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 06)Jonathan Engelsma
 
So You Want To Be a Beekeeper?
So You Want To Be a Beekeeper? So You Want To Be a Beekeeper?
So You Want To Be a Beekeeper? Jonathan Engelsma
 
What Every IT Manager Should Know About Mobile Apps
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 AppsJonathan Engelsma
 
2013 Michigan Beekeepers Association Annual Spring Conference
2013 Michigan Beekeepers Association Annual Spring Conference2013 Michigan Beekeepers Association Annual Spring Conference
2013 Michigan Beekeepers Association Annual Spring ConferenceJonathan 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...
2012 Michigan Beekeepers Association Annual Spring Conference - Beekeepers On...Jonathan Engelsma
 

Más de Jonathan Engelsma (13)

Knowing Your Bees: Becoming a Better Beekeeper
Knowing Your Bees: Becoming a Better BeekeeperKnowing Your Bees: Becoming a Better Beekeeper
Knowing Your Bees: Becoming a Better Beekeeper
 
BIP Hive Scale Program Overview
BIP Hive Scale Program OverviewBIP Hive Scale Program Overview
BIP Hive Scale Program Overview
 
Selling Honey Online
Selling Honey OnlineSelling Honey Online
Selling Honey Online
 
Selling Honey at Farmers Markets, Expos, etc.
Selling Honey at Farmers Markets, Expos, etc. Selling Honey at Farmers Markets, Expos, etc.
Selling Honey at Farmers Markets, Expos, etc.
 
Harvesting and Handling Honey for Hobby and Small Sideline Beekeepers
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
 
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)
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 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)
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 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)
iOS Bootcamp: learning to create awesome apps on iOS using Swift (Lecture 06)
 
So You Want To Be a Beekeeper?
So You Want To Be a Beekeeper? So You Want To Be a Beekeeper?
So You Want To Be a Beekeeper?
 
What Every IT Manager Should Know About Mobile Apps
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
 
Mobile Gamification
Mobile GamificationMobile Gamification
Mobile Gamification
 
2013 Michigan Beekeepers Association Annual Spring Conference
2013 Michigan Beekeepers Association Annual Spring Conference2013 Michigan Beekeepers Association Annual Spring Conference
2013 Michigan Beekeepers Association Annual Spring Conference
 
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...
2012 Michigan Beekeepers Association Annual Spring Conference - Beekeepers On...
 

Último

MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 

Último (20)

MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 

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.