0% found this document useful (0 votes)
37 views79 pages

Lec03 - 01 (Swift1)

The document provides an overview of the Swift programming language, including its history, data types, variables, constants, and features such as optionals and type safety. It outlines the evolution of Swift since its introduction in 2014 and discusses key programming concepts like tuples, collections, and type casting. Additionally, it covers string manipulation and initialization, emphasizing Swift's modern syntax and safety features.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views79 pages

Lec03 - 01 (Swift1)

The document provides an overview of the Swift programming language, including its history, data types, variables, constants, and features such as optionals and type safety. It outlines the evolution of Swift since its introduction in 2014 and discusses key programming concepts like tuples, collections, and type casting. Additionally, it covers string manipulation and initialization, emphasizing Swift's modern syntax and safety features.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 79

CIS651: Mobile Application

Programming

Swift Programming Language (1)

Dr. Hong Martel


[email protected]
Outline
1. Swift, the Basics
 History of Swift
 Data Types
 Variables and Constants
2. Strings and Characters
3. Collection Types
 Arrays
 Sets
 Dictionaries
The History of Swift
(1)is a new language that Apple introduced in 2014.
● Swift
● It replaces Objective-C as the recommended development
language for iOS and Mac.
● Meant to address memory and type safety issues present in
Objective-C
● Switches the message-passing syntax of Objective-C for
the more common dot notation found in Java, etc.
● Uses Objective-C runtime, so it can import any
Objective-C libraries
The History of Swift
(2)
● The language itself looks much more “Java-like” with
many keywords carried over
● In general, shouldn’t take too long for a Java programmer
to pick up
● Semicolons not required though
● Builds in many of the old standard Apple data types (like
NSString)
● Swift introduces various advanced features while relying on
the same tested, elegant iOS frameworks that developers have
built upon for years.
The History of Swift
● (3)
Swift 1 officially released in September 2014

● Swift 2 released in September 2015

● Open sourced in December 2015

● Swift 3 released in September 2016

● Swift 4 released in September 2017

● Swift 5 released in March 2019

● Swift 6 released in September 2024


https://www.hackingwithswift.com/articles/269/whats-new-in-swift-6
Date Types
● Swift types can be arranged into three basic groups:
structures, classes, and enumerations

● Swift’s structures (or “structs”) and enumerations (or


“enums”) are significantly more powerful than in most
languages.
● In addition to supporting properties, initializers, and methods,
they can also conform to protocols and can be
Standard Data types
● All of standard data types are structures:
● Numbers Int, Float, Double
: Bool
● Boolean: String, Character
● Text:
Collections: Array<T>,
Dictionary<K:Hashable,V>,
Set<T:Hashable>

● Therefore all standard types have properties, initializers,


and methods of their own. They can also conform to
protocols and be extended.
Variables and Constants
● The var keyword denotes a
● var nextYear:
variable. Int //Integer variable
● var outsideTemp: Float //Floating-point variable
● var hasPet: Bool //Boolean variable

● The let keyword denotes a constant value, which cannot


be changed.
● let constInt: Int //declares a constant
constInt = 7 //sets constInt to 7
constInt = 9 //will give an ERROR

● In Swift, you should use let unless you expect the value
will need to change.
Tuples (1)
● What is a tuple?
● It is a group of values.You can use it anywhere you can use a type.
let x: (String, Int, Double) = (“hello”, 5, 0.85)
let (word, number, value) = x

print(word) ---------?
print(number) ---------?
print(value) ---------?

● The tuple elements can be


named when the tuple is
declared
let x: (w: String, i: Int, v: Double) = (“hello”, 5, 0.85)
print(x.w)
print(x.i)
let y = //Elements of y named with the assignment
xprint(x.v)
Tuples (2)
● What is a tuple?
● It is a group of values.You can use it anywhere you can use a type.
let x: (String, Int, Double) = (“hello”, 5, 0.85)
let (word, number, value) = x

print(word) // prints hello


print(number) // prints 5
print(value) // prints 0.85

● The tuple elements can be


named when the tuple is
declared
let x: (w: String, i: Int, v: Double) = (“hello”, 5, 0.85)
print(x.w) // prints hello
print(x.i)
let y = // prints 5 of y named with the assignment
//Elements
print(x.v) // prints 0.85
x
Example use of tuples - Function return
(1)
● Returning multiple values from a function

func getSize() -> (weight: Double, height: Double) {


return (250, 80)
}
let x = getSize()
print(“weight is \(x.weight)”) – string interpolation
---------?
… OR …

print(“height is \(getSize().height)”) ---------?


Example use of tuples - Function
return(2)
● Returning multiple values from a function

func getSize() -> (weight: Double, height: Double) {


return (250, 80)
}
let x = getSize()
print(“weight is \(x.weight)”) // weight is 250

… OR …

print(“height is \(getSize().height)”) // height is 80


Naming
● Cannot begin with a number
● Case sensitive
● Cannot contain whitespace characters,
mathematical symbols, invalid unicode, arrows, ...
● Don’t use reserved Swift keyword as a variable or
constant
● Non-meaningful names are strongly discouraged
● Multiple constants or multiple variables on a single
line, separately by commas

var x, y, z:Double – correct, but discouraged


Option
al
● Swift types can be optional, which is indicated
by appending ? to a type name.

● An optional lets you express the possibility that a variable


may not store a value at all.
● The value of an optional will either be an instance of
the specified type or nil.
● You can assign values to an optional just like any
other variable.
Unwrapping an
Optional
● You cannot use optional variables like non-optional
variables– even if they have been assigned values.

● Before you can read the value of an optional variable, you


must address the possibility of its value being nil.This
is called unwrapping the optional.

● There are two ways of unwrapping.


● Forced unwrapping
● Optional binding
Forced
● ToUnwrapping
forcibly unwrap an optional, you append a ! to its
name.

● When you forcibly unwrap an optional, you tell the


compiler that you are sure that the optional will not be
nil and can be treated as if it were a normal Float.
● But what if you are wrong?
Optional
● ABinding
safer way to unwrap an optional is optional binding.
Optional binding works within a conditional if-let
statement.You assign the optional to a temporary constant.
If your optional has a value, then the assignment is valid and
you proceed using the non-optional constant. If the optional
is nil, then you can handle that case with an else
clause.
What is really an
Optional?
● An Optional is just an enum. In other words …
enum Optional<T> { //<T> is a generic type
case None
case Some(T)
}

let x: String? = nil var y = x!


… is …
let x = Optional<String>.None … is …
switch x {
let x: String? = “hello” case .Some
… is … (let
let x = value): y
Optiona = value
l<Strin case .None
g>.Some : // raise
(“hello an
Optional
Chaining
● Optionals can be “chained”
var questionLabel: UILabel? //imagine this is an @IBOutlet
without the implicit unwrap !
if let label = questionLabel {
if let text = label.text
{ let x =
text.hashValue
...
}
}
… or …

if let x =
questionLabel?.text?.hashValue {
...
Type Safe and Type
Inference
● Swift is a type-safe language

● Swift performs type checks when compiling your code


and flags any mismatched types as errors

● Type inference is particularly useful when you declare


a constant or variable with an initial value

1 let va r1 =30 / / var1 i s i n f e r re d t o t y p e I n t


2 let var2=1.23456 / / var2 i s i n f e r re d t o t y p e Double
3 l e t v a r 3 = var1+var2 / / var3 i s i n f e r re d t o t y p e Double
Inferring Types
● Type Inference: The compiler can infer types of variables
from their initial values.This is called type inference.
var helloStr = "Hello, playground" "Hello, playground"
helloStr = "Hello, Swift" "Hello, Swift"
let constHelloStr = helloStr "Hello, Swift"
constHelloStr = "Hello, world“ //error

● Note: if you use type inference for a floating-point literal, the


type defaults to Double.
let easyPI = 3.14 //easyPI will be a double
An Example
class Employee {
var name: String //variable stored property
let ID: Int //constant stored property
let birthYear: Int //constant stored property
var age: Int { //computed property
return 2018 - birthYear
}
init(name: String, ID: Int, birthYear: Int) {//initializer
self.name = name
Swift provides a default
self.ID = ID initializer for any structure or
self.birthYear = birthYear class that provides default
} values for all of its properties
and doesn’t provide at least
}
one initializer itself.
var emp = Employee(name: "John Doe",
ID: 1, birthYear: 2000)
print(emp.name) //prints John Doe
print(emp.ID) //prints 1
print(emp.birthYear) //prints 2000
print(emp.age) //prints 18
Type
casting
● Type casting is a way to check the type of an instance, or to
treat that instance as a different class from somewhere else
in its own class hierarchy.

● Type casting in Swift is implemented with the is and as


operators. These two operators provide a simple and
expressive way to check the type of a value or cast a value
to a different type.
Consider the class
hierarchy
class MediaItem
{ var name:
String
init(name: String) {
self.name = name
}
}
class Movie: MediaItem {
var director: String
init(name: String, director: String) {
self.director = director
super.init(name: name)
class Song: MediaItem {
}
} var artist: String
init(name: String, artist: String){
self.artist = artist
super.init(name: name)
}
}
And create an array with Movie
and Song items
let library = [
Movie(name: "Casablanca", director: "Michael Curtiz"),
Song(name: "Blue Suede Shoes", artist: "Elvis Presley"),
Movie(name: "Citizen Kane", director: "Orson Welles"),
Song(name: "The One And Only", artist: "Chesney Hawkes"),
Song(name: "Never Gonna Give You Up", artist: "Rick Astley")
] // the type of "library" is inferred to be [MediaItem]

● The type of the library array is inferred by initializing it


with the contents of an array literal. Swift’s type checker is able
to deduce that Movie and Song have a common superclass
of MediaItem, and so it infers a type of [MediaItem]
for the library array.
Checking Type
(is)
● Use the type check operator (is) to check whether an instance is of
a certain subclass type.The type check operator returns true if
the instance is of that subclass type and false if it is not.
var movieCount = 0
var songCount = 0
for item in library {
if item is Movie {
movieCount += 1
} else if item is Song {
songCount += 1
}
}
print("Media library contains \(movieCount) movies and \(songCount)
songs")
// Prints "Media library contains 3 movies and 2 songs" ??
Downcasting (as? or
as!)
● A constant or variable of a certain class type
may actually refer to an instance of a subclass
behind the scenes. Where you believe this is
the case, you can try to downcast to the
subclass type with a type cast operator (as? or
as!).
● Use the conditional form of the type cast operator (as?) when
you are not sure if the downcast will succeed.This form of the
operator will always return an optional value, and the value will
be nil if the downcast was not possible.This enables you to
check for a successful downcast.

● Use the forced form of the type cast operator (as!) only when
you are sure that the downcast will always succeed.This form of
the operator will trigger a runtime error if you try to downcast
to an incorrect class type.
Downcasting
for example
item in library {
if let movie = item as? Movie {
print("Movie: \(movie.name), dir. \(movie.director)")
} else if let song = item as? Song
{ print("Song: \(song.name), by \
(song.artist)")
}
}
// Movie: Casablanca, dir. Michael Curtiz
// Song: Blue Suede Shoes, by Elvis Presley
// Movie: Citizen Kane, dir. Orson Welles
// Song: The One And Only, by Chesney Hawkes
// Song: Never Gonna Give You Up, by Rick Astley
QOD– Question of the Day
Password:

What will happen when the following swift code is executed?


var anotherOptionInt: Int?
let anotherInt = anotherOptionInt!

o value of anotherOptionalInt will be assigned to anotherInt


o anotherInt will be assigned an integer value due to type
inference
o will crash
o anotherInt will be nil because anotherOptionalInt is not
initialized
Outline
1. Swift, the Basics
 History of Swift
 Data Types
 Variables and Constants
2. Strings and Characters
3. Collection Types
 Arrays
 Sets
 Dictionaries
String Literals
● String literal as an initial value
let someString = "Some string literal value"

● Multi-line string literal


1 let quotation = """
2 The White Rabbit put on his spectacles. "Where shall I begin,
3 please your Majesty?" he asked.
4
5 "Begin at the beginning," the King said gravely, "and go on
6 t i l l you come to the end; then stop."
7 """
Initializing an Empty
String
● Create an empty string
var emptyString = "" / / empty string literal
var anotherEmptyString = String() / / initializer syntax

/ / these two strings are both empty, and are equivalent to each other

● Checking empty
if emptyString.isEmpty {
print("Nothing to see here")
}
/ / Prints "Nothing to see here"
Working with Strings and
Characters ······
[1]
● Character constant or variable
let que stionMa rk : Character = "?"
let catCharacters : [Character] = ["C" ,"a" ,"t" ]
let catString=String(catCharacters)
p r i n t ( c a t S t r i n g ) / / P r i n t s "Cat"

● Accessing the individual Character values


for character in catString
{ print(character)
}
Working with Strings
and Characters ··
·● ·Concatenating
· · [2] Strings and Characters
let string1 = "hello"
let string2 = " there"
var welcome= s t r i n g 1 + s t r i n g 2
/ / welcome now equals " h e l l o t h e re "

v a r i n s t r u c t i o n = " l o o k over"
instruction += string2
/ / i n s t r u c t i o n now equals "look over
t h e re "

let exclamationMark : Character = "!"


welcome.append(exclamationMark)
/ / welcome now equals " h e l l o t h e re ! "
String
Interpolation
● Construct a new String value from a mix of constants,
variables, literals, and expressions by including their
values inside a string literal
let multiplier=3
let message="\(multiplier)times 2.5 is\
(Double(multiplier)*2.5)"
/ / message i s "3 tim es 2 . 5 i s 7 . 5 "
Accessing and
Modifying a String
· · · · · · [1]
● Each String value has an associated index type,
String.Index
• startIndex property to access the position of the first Character
of a String

• endIndex property is the position after the last character in a


String, and it isn’t a valid argument to a string’s subscript

• if a String is empty, startIndex = endIndex


l e t g r e e t i n g =" Gut e n Tag!"
greeting[greeting.startIndex] / / G
greeting[greeting.index(before: greeting.endIndex)] / / !
greeting[greeting.index(after: greeting.startIndex)] / / u
l e t i n d e x = g r e e t i n g . i n d e x ( g r e e t i n g . s t a r t I n d e x , o ff s e t B y : 7 )
greeting[index] / / a
Accessing and
Modifying a String
· · · · · · [2]
● Accessing an index outside of the range
g r e e t i n g [ g r e e t i n g . e n d I n d e x ] / / Error
g r e e t i n g . i n d e x ( a f t e r : g r e e t i n g . e n d I n d e x ) / / Error

● Using the indices property


for index in greeting.indices{ print("\
(greeting[index] )", terminator:"")
}
// Prints "Guten Tag! "
Accessing and Modifying
a String ·
● · · · · · [3]
Inserting
var welcome = "hello"
w e l c o m e . i n s e r t ( " ! " , a t : welcome.endIndex)
/ / welcome now equals " h e l l o ! "

w e l c o m e . i n s e r t ( c o n t e n t s O f : " t h e r e " , a t : we l c o m e .i n d e x (b e fo r e : welcome. e n d I n d e x ))


/ / welcome now e q u a l s " h e l l o t h e re ! "

● Removing
welcome.remove(at: welcome.index(before: welcome.endIndex))
/ / welcome now equals " h e l l o t h e re "

l e t r a n g e = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex


welcome.removeSubrange(range)
/ / welcome now equals " h e l l o "
Accessing and
Modifying a String

· · · · · [4]
Substrings
l e t g r e e t i n g = " H e l l o , world!"

l e t i n d e x = g r e e t i n g . i n d e x ( o f : " , " ) ?? gr e e t i n g. e n d Ind e x

let beginning = greeting[..<index]


/ / beginning i s "Hello"

/ / Convert t h e re s u l t t o a S t r i n g f o r long-term s t o r a g e .
l e t n e wSt r i n g = St ri ng (b e g i n ni ng )

Nil Coalescing Operator, also called default


??:
operator
Question Of the Day – Password:

Better Online Swift Complier:


https://www.tutorialspoint.com/
compile_swift_online.php
What is the value of greeting[idx] after the following Swift
code block has been executed?
var greeting: String = "Hello, Androd!"
let index = greeting.firstIndex(of: ",") ??
greeting.endIndex
var idx = greeting.index(index, offsetBy: -3)
greeting[idx]
Outline
1. Swift, the Basics
 History of Swift
 Data Types
 Variables and Constants
2. Strings and Characters
3. Collection Types
 Arrays
 Sets
 Dictionaries
Collection Types
● The Swift standard library offers three collections:
● Arrays: Ordered collections of values
● Sets: Unordered collections of unique values.
● Dictionaries: Unordered collections of key-value
associations.
Arrays
● An array is an ordered collection of elements.The array type is
written as Array<T>, where T is the type of element that
the array will contain. Arrays can contain elements of any
type: a standard type, a structure, or a class.
● Arrays are strongly typed. Once you declare an array as
containing elements of, say, Int, you cannot add a String
to this array.
● Declaration:
var arrayOfInts: Array<Int> //Integer array
var arrayOfInts: [Int] //shorthand
notation
Creating an Empty Array
● You can create an empty array of a certain type using
initializer syntax:
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
//Prints "someInts is of type [Int] with 0 items.“

You can append an item to the array using the append(_:)


method:
someInts.append(3)
//someInts now contains 1 value of type Int
Creating an Array with a Default
Value
● Swift’s Array type also provides an initializer for
creating an array of a certain size with all of
its values set to the same default value.You
pass this initializer the number of items to be
added to the new array (called count) and a
default value of the appropriate type (called
repeatedValue):
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
//threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
Creating an array by adding two
Arrays together
● You can create a new array by adding together
two existing arrays with compatible types
with the addition operator (+).The new
array’s type is inferred from the type of the
two arrays you add together:
var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
//threeDoubles is of type [Double], and equals
[0.0, 0.0, 0.0]
var anotherThreeDoubles = [Double](count: 3,
repeatedValue: 2.5)
//anotherThreeDoubles is of type [Double], and equals
[2.5, 2.5, 2.5]
var sixDoubles = threeDoubles + anotherThreeDoubles
//sixDoubles is inferred as [Double], and equals
[0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
Creating an Array with an
Array Literal
● You can also initialize an array with an array literal, which is a
shorthand way to write one or more values as an array
collection. An array literal is written as a list of values, separated
by commas, surrounded by a pair of square brackets:

var shoppingList: [String] = ["Eggs", "Milk"]


//shoppingList has been initialized with two initial items

Using type inference, we can write a shorter form


as
var shoppingList = ["Eggs", "Milk"]
Accessing and Modifying
an Array: the isEmpty
Property
● Use the Boolean isEmpty property as a shortcut
for checking whether the count property is equal
to 0:

if shoppingList.isEmpty {
print("The shopping list is empty.")
}
else {
print("The shopping list is not empty.")
}
//Prints "The shopping list is not empty."
Adding items to an
● Array
You can add a new item to the end of an array by calling
the array’s append(_:) method:
shoppingList.append("Flour")
// shoppingList now contains 3 items

● Alternatively, append an array of one or more compatible


items with the addition assignment operator (+=):
shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese",
"Butter"]
// shoppingList now contains 7 items
Subscripting
● You can also use subscript syntax to change a range of
values at once, even if the replacement set of values has a
different length than the range you are replacing. The
following example replaces "Chocolate Spread",
"Cheese",
and "Butter" with "Bananas" and "Apples":

shoppingList[4...6] = ["Bananas", "Apples"]


// shoppingList now contains 6 items
Inserting an item into an
● ToArray
insert an item into the array at a specified index, call
the array’s insert(_:atIndex:) method:

shoppingList.insert("Maple Syrup", atIndex: 0)


// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the
list

● This call to the insert(_:atIndex:) method inserts


a new item with a value of "Maple Syrup" at the very
beginning of the shopping list, indicated by an index of 0.

● Note, insert(_:atIndex:)does not replace the


item at atIndex. Rather, it pushes back items starting
Removing an item from an
● YouArray
can Remove an item from the array with the
removeAtIndex(_:) method.This method removes the item at the
specified index and returns the removed item (although you can ignore the
returned value if you do not need it):
let mapleSyrup = shoppingList.removeAtIndex(0)
// the item that was at index 0 has just been removed
// shoppingList now contains 6 items, and no Maple Syrup
// the mapleSyrup constant is now equal to the removed
"Maple Syrup" string

● Any gaps in an array are closed when an item is removed, and so the value
at index 0 is once again equal to "Six eggs":
firstItem = shoppingList[0]
// firstItem is now equal to "Six eggs"
Removing the last item
● If you want to remove the final item
from an array, use the removeLast()
method rather than the
removeAtIndex(_:) method to avoid
the need to query the array’s count
property. Like the
removeAtIndex(_:) method,
removeLast() returns the removed
item:

let apples = shoppingList.removeLast()


// the last item in the array has just
been removed
// shoppingList now contains 5 items, and
no apples
Iterating over an array
for i in 0..<shoppingList.count {
print("\(shoppingList[i])")
}

// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
Iterating over an array
contd.
Or, alternatively

for i in 0...(shoppingList.count-1) {
print("\(shoppingList[i])")
}

// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
Iterating over an Array contd.
● You can iterate over the entire set of values in an array
with the for-in loop:

for item in shoppingList {


print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
Iterating using
enumerate()
● If you need the integer index of each item as well as its value,
use the enumerate() method to iterate over the array
instead.
● For each item in the array, the enumerate() method returns
a
tuple composed of the index and the value for that
item.
● You can decompose the tuple into temporary constants or variables as
part of the iteration:

// Item 1: Six eggs


for (index, value) in shoppingList.enumerate() {
// Item 2: Milk
print("Item \(index + 1): \(value)")
// Item 3: Flour
}
// Item 4: Baking Powder
// Item 5: Bananas
Sets
● A set stores distinct values of the same type in a collection
with no defined ordering.You can use a set instead of an
array when the order of items is not important, or when
you need to ensure that an item only appears once.
Creating and Initializing an
empty
● Set
You can create an empty set of a certain type using
initializer syntax:
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// Prints "letters is of type Set<Character> with 0 items.“

letters.insert("a")
// letters now contains 1 value of type Character
Creating a Set with an Array
Literal
● You can initialize a set with an array literal
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items

● A set type cannot be inferred from an array literal alone, so the type Set must
be explicitly declared. However, because of Swift’s type inference, you don’t
have to write the type of the set if you’re initializing it with an array literal
containing values of the same type.The initialization of favoriteGenres
could have been written in a shorter form instead:
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]

● You can add a new item into a set by calling the set’s insert(_:) method:
favoriteGenres.insert("Jazz")
// favoriteGenres now contains 4 items
Removing an item from a
● YSet
ou can remove an item from a set by calling the
set’s remove(_:) method, which removes the item if it’s
a member of the set, and returns the removed value, or
returns nil if the set did not contain it.
● Alternatively, all items in a set can be removed with
its removeAll() method.
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre)? I'm over it.")
} else {
print("I never much cared for that.")
}
// Prints "Rock? I'm over it."
Checking a Set for an
Item
● To check whether a set contains a particular item,
use the contains(_:) method.

if favoriteGenres.contains(“Folk") {
print(“Folk is in the set.")
} else {
print(“Folk is not in the set.")
}
// Prints “Folk is not in the set."
Iterating over a Set
● You can iterate over the values in a set with a for-in
loop.

for genre in favoriteGenres {


print("\(genre)")
}
// Classical
// Jazz
// Hip hop
Iterating in an order
● Swift’s Set type does not have a defined ordering.To iterate
over the values of a set in a specific order, use
the sort() method, which returns the set’s elements as
an array sorted using the < operator.

for genre in favoriteGenres.sort() {


print("\(genre)")
}
// Classical
// Hip hop
// Jazz
Dictionaries
● A dictionary stores associations between keys of the same type and
values of the same type in a collection with no defined ordering.
● Each value is associated with a unique key, which acts as an identifier
for that value within the dictionary. Unlike items in an array, items in a
dictionary do not have a specified order.
● You use a dictionary when you need to look up values based on their
identifier, in much the same way that a real-world dictionary is used
to look up the definition for a particular word.
Dictionary Type Syntax
● The type of a Swift dictionary is written in full as
Dictionary<Key, Value>, where Key is the type
of value that can be used as a dictionary key, and Value is
the type of value that the dictionary stores for those keys.

● Shorthand notation:You can also write the type of a


dictionary in shorthand form as [Key: Value].
Although the two forms are functionally identical, the
shorthand form is preferred.
Creating an Empty
Dictionary
● You can create an empty Dictionary of a certain type by
using initializer syntax:
var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String]
dictionary

● This example creates an empty dictionary of type [Int: String]


to store names of integer values.
● Its keys are of type Int, and its values are of type String.
Creating a Dictionary with a
Dictionary Literal
● You can initialize a dictionary with a dictionary literal, which
consists of one or more key-value pairs.
var airports: [String: String] = ["YYZ": "Toronto Pearson",
"DUB": "Dublin"]
● The airports dictionary is declared as having a type of [String:
String], which means a Dictionary whose keys (Airport Codes) are of
type String, and whose values (Airport Names) are also of type
String.

● Using the type inference of Swift, the initialization of airports


could have been written in a shorter form instead:
var airports = ["YYZ": "Toronto Pearson",
"DUB": "Dublin"]
● Swift can infer that [String: String] is the correct type to use
The count and isEmpty
property
● You can find out the number of items in a Dictionary by checking its
read- only count property:
print("The airports dictionary contains \(airports.count)
items.")
// Prints "The airports dictionary contains 2 items.“

● Use the Boolean isEmpty property as a shortcut for checking


whether the count property is equal to 0:
if airports.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary is not empty.")
}
//Prints "The airports dictionary is not empty."
Adding/Modifying using
Subscripting
● You can add a new item to a dictionary with subscript
syntax. Use a new key of the appropriate type as the
subscript index, and assign a new value of the appropriate
type:
airports["LHR"] = "London"
// the airports dictionary now contains 3 items

● You can also use subscript syntax to change the


value associated with a particular key:
airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London
Heathrow"
Adding/Modifying using
updateValue(_:forKey:)
● As an alternative to subscripting, use a dictionary’s
updateValue(_:forKey:)method to set or update the value for
a particular key.
● Like the subscript examples earlier, the updateValue(_:forKey:)
method sets a value for a key if none exists, or updates the value if that key already
exists.
● Unlike a subscript, however, the updateValue(_:forKey:) method
returns the old value after performing an update.This enables you to check
whether or not an update took place.

● The updateValue(_:forKey:) method returns an optional value


of the dictionary’s value type.
● For a dictionary that stores String values, for example, the method returns a
value of type String?, or “optional String”.
● This optional value contains the old value for that key if one existed before
the update, or nil if no value existed:
Example:
updateValue(_:forKey:)
if let oldValue = airports.updateValue("Dublin Airport", forKey:
"DUB") { print("The old value for DUB was \(oldValue).")
}
// Prints "The old value for DUB was Dublin."
Retrieving using Subscripting
● You can also use subscript syntax to retrieve a value from the dictionary
for a particular key.
● Because it is possible to request a key for which no value exists, a
dictionary’s subscript returns an optional value of the dictionary’s value
type.
● If the dictionary contains a value for the requested key, the subscript returns
an optional value containing the existing value for that key. Otherwise, the
subscript returns nil:

if let airportName = airports["DUB"] {


print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports
dictionary.")
}
Removing a key-value
pair using subscripting
● You can use subscript syntax to remove a key-value pair
from a dictionary by assigning a value of nil for that key:

airports["APL"] = "Apple International"


// "Apple International" is not the real airport
for APL, so delete it
airports["APL"] = nil
// APL has now been removed from the dictionary
Removing a key-value pair
using
removeValueForKey(_:)
● Alternatively, remove a key-value pair from a dictionary with
the remove ValueForKey(_:) method. This method
removes the key-value pair if it exists and returns the
removed value, or returns nil if no value existed:
if let removedValue = airports.removeValueForKey("DUB")
{ print("The removed airport's name is \
(removedValue).")
} else {
print("The airports dictionary does not contain a value for
DUB.")
}
// Prints "The removed airport's name is Dublin Airport."
Iterating over a
Dictionary
● You can iterate over the key-value pairs in a dictionary
with a for-in loop. Each item in the dictionary is
returned as a (key, value) tuple, and you can
decompose the tuple’s members into temporary constants
or variables as part of the iteration:

for (airportCode, airportName) in airports {


print("\(airportCode): \
(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow
Arrays from
● IfDictionaries
you need to use a dictionary’s keys or values with an
API that takes an Array instance, initialize a new array
with the keys or values property:

let airportCodes = [String](airports.keys)


// airportCodes is ["YYZ", "LHR"]
let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London
Heathrow"]
Question Of the Day – Password:

Better Online Swift Complier:


https://www.tutorialspoint.com/
compile_swift_online.php
Show two ways of creating an empty array of integers.
Questions?

You might also like