Professional Documents
Culture Documents
Swift Basics
Swift Basics
Array:
We can create constants and variables of arrays just like other types of data, but the
difference is that arrays hold many values inside them.
var x : [Int] = []
Sets:
Sets are collections of values just like arrays, except they have two differences:
2. No duplicates.
7. Both sets and arrays are collections of data, meaning that they hold multiple
values inside a single variable. However, how they hold their values is what
matters: sets are unordered and cannot contain duplicates, and fast retrival
whereas arrays retain their order and can contain duplicates.
We can’t access elements from set using index as we do in arrays.
Tuples allow you to store several values together in a single value. That might sound
like arrays, but tuples are different:
1. You can’t add or remove items from a tuple; they are fixed in size.
2. You can access items in a tuple using numerical positions or by naming them, but Swift
won’t let you read numbers or names that don’t exist.
Dictionary:
//update element
capitalCity[“Japan”] = “T”
Updated Dictionary: ["Nepal": "Kathmandu", "England": "London", "Japan": "T"]
print("Keys: Values")
Empty dictionaries:
var emptyDictionary = [Int: String]()
var empDict: [Int:String] = [:]
Dictionaries don’t store our items using an index, but instead they optimize the way
they store items for fast retrieval. So, when we say user["country"] it will send
back the item at that key (or nil) instantly, even if we have a dictionary with 100,000
items inside.
If you try to read a value from a dictionary using a key that doesn’t exist, Swift will
send you back nil – nothing at all. While this might be what you want, there’s an
alternative: we can provide the dictionary with a default value to use if we request a
missing key.
let favoriteIceCream = [
"Paul": "Chocolate",
"Sophie": "Vanilla"
]
favoriteIceCream["Charlotte"]
But if we tried reading the favorite ice cream for Charlotte, we’d get back nil,
meaning that Swift doesn’t have a value for that key:
We can fix this by giving the dictionary a default value of “Unknown”, so that when
no ice cream is found for Charlotte we get back “Unknown” rather than nil:
favoriteIceCream["Charlotte", default: "Unknown"]
let historyResult = results["history", default: 0]
Whenever you read a value from a dictionary, you might get a value back or you
might get back nil – there might be no value for that key. Having no value can cause
problems in your code, not least because you need to add extra functionality to
handle missing values safely, and that’s where dictionary default values come in: they
let you provide a backup value to use for when the key you ask for doesn’t exist.