Lec03 - 01 (Swift1)
Lec03 - 01 (Swift1)
Programming
● 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) ---------?
… OR …
if let x =
questionLabel?.text?.hashValue {
...
Type Safe and Type
Inference
● Swift is a type-safe language
● 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:
/ / 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"
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 "
● Removing
welcome.remove(at: welcome.index(before: welcome.endIndex))
/ / welcome now equals " h e l l o t h e re "
/ / 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 )
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
● 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:
// 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:
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.