Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Swift Basics:

Array:

Arrays are collections of values that are stored as a single value.

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.

Ex: var color = [“red”,”green”,”yellow”]

Declare empty array –

var x = [] // please give type annotation

var x : [Int] = []

Note: If you’re using type annotations, arrays are written in


brackets: [String], [Int], [Double], and [Bool].

Ex: color.count, color.first, color.last, color[2],

Color.append(“white”) // add element at end

Color.insert(“blue”, at: 2) // add element at particular place

Sets:

Sets are collections of values just like arrays, except they have two differences:

1. Items are in random order.

2. No duplicates.

3. let colors = Set(["red", "green", "blue"])


4. If you try to insert a duplicate item into a set, the duplicates get ignored. For
example:

5. let colors2 = Set(["red", "green", "blue", "red",


"blue"])
6. The final colors2 set will still only include red, green, and blue once.

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.

3. Tuples are created by

var name = (first: "Taylor", last: "Swift")

we can access by numerical positions or by names.(name.0 or name.first)

Another advantage to tuples is that each value is specifically created by you, so as


well as providing a name you also provide a type. So, you could create a tuple like
this one:

var person = (name: "Paul", age: 40, isMarried: true)

Dictionary:

Swift dictionary is an unordered collection of items. It stores elements


in key/value pairs. Here, keys are unique identifiers that are associated
with each value.

var capitalCity = ["Nepal": "Kathmandu", "England": "London"]


print(capitalCity)

["Nepal": "Kathmandu", "England": "London"]


// add element to dictionary
capitalCity["Japan"] = "Tokyo"
Updated Dictionary: ["Nepal": "Kathmandu", "England": "London", "Japan": "Tokyo"]

//update element
capitalCity[“Japan”] = “T”
Updated Dictionary: ["Nepal": "Kathmandu", "England": "London", "Japan": "T"]

var cities = ["Nepal":"Kathmandu", "China":"Beijing", "Japan":"Tokyo"]


// cities.keys return all keys of cities
var countryName = Array(cities.keys)
var capitalName = Array(cities.values)
print("Keys: ", countryName)
Keys: ["Nepal", "Japan", "China"]

var removedValue = cities.removeValue(forKey: “Nepal”) // remove value from dict


print(cities.count) // return count of dictionaries

//iterate over dictionary


var classification = ["Fruit": "Apple", "Vegetable": "Broccoli", "Beverage": "Milk"]

print("Keys: Values")

for (key,value) in classification {


print("\(key): \(value)")
}

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.

You might also like