Informative Swift Part 2: A Brief Knowledge of Array, Set, Tuple and Dictionary.

Array:?

Arrays are collections of the Same types of value.

Declaration:

let nameArray = ["Tarun", "Barun"]        

In the above declaration, two String types of data have been added in an array named nameArray.?

To declare an empty array of a specific data type we use the following format.

var arrayName = [String]()        

Access value from the array:

Value from the array is accessed using the index.

The index of the array starts from 0, so the first value of an array will be in the zero position.

let name = arrayName[0]        

Note: Swift crashes if you read an item from an array that doesn’t exist

In a variable (var) array, you can add, remove or rearrange items. But you are not allowed to do so in a constant (let) array.

Some useful functions of Array:

nameArray.append("Sonu") // adding a new value

nameArray.remove(at: 0) // removing a value of zero index

let length = nameArray.count // getting the number of values
        

Traversing through the values:

let nameArray = ["Tarun", "Barun"]

for value in nameArray{
? ? print(value)
}
// OR

nameArray.forEach { value in

? ? print(value)

}        


Set:?

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

  1. Here, Items aren’t stored in any order; they are stored randomly.
  2. No item can appear twice in a set, which means all items must be unique.

You can create sets directly from arrays, like this:

let colors = Set(["yellow", "green", "red"])        

Note: In Swift the contains() function complexity is O(1) for a Set

Sets are more useful If you want to check whether a value appears in a dictionary or not, as you don’t have duplicates, you can do a fast look-up.

Some useful methods:

var nameSet = Set<String>() // Declaration of an empty Set

nameSet.insert("Tarun") // add value

nameSet.remove("Tarun") // remove value
 
nameSet.count // count of values.        


Tuple:

A tuple is a group of different values. And, each value inside a tuple can be of different or the same data types.

  1. You can’t add or remove items from a tuple, they are fixed in size.
  2. You can change the values inside a tuple but not the types of values.
  3. You can access items in a tuple using numerical positions or by their them.

Declaration:

var name = (first: "Tarun", last: "Biswas")        

We can access the value of the Tuple in any of the following ways.

let myFirstName = name.0 // using index

let myFirstName = name.first // Using name        

Passing Tuple as a parameter:

var name = (first: "Tarun", last: "Biswas") // Declaration

let fullName = getFullName(myName: name) // Passing tuple to method

func getFullName(myName : (String, String))-> String { // myName accepts a Tuple
????return ("\(myName.0) \(myName.1)")
}        

Note: Tuples in Swift hold very specific types of data like a struct.

The main use of Tuple is returning multiple values from a function call.

Dictionary:

A Swift dictionary is an unordered collection of items. It stores elements in key-value pairs.

Declaration:

var dic = [String: String]() // Declaration.

var someVar = dic[key] // accessing value from a dictionary

var capitalCity = ["Bangladesh": "Dhaka", "Italy": "Rome"] // Declaration with some values.        

Accessing Value:

Unlike an array, you can access dictionary value using the key whereas an array uses the index to access that.

var someVar = dic[key]        

Note: Dictionary keys are always unique. But it allows it's one key to be nil.?

Swift returns nil if a key does not exist in the dictionary. As there is a chance of getting a nil value, the value we get from a dictionary is always optional.?

Using Default Value :

We can set a default value to the Swift dictionary to avoid a nil value. You know, the key and value both can be nil, if you are searching for a value using a key that is not present in the dictionary, then the default value will be returned.

var capitalCity = ["Bangladesh": "Dhaka", "Italy": "Rome"] 
let capitalOfIndia = capitalCity["India", default: "New Delhi"] //New Delhi will be returned as 
                                                                //there is no such key India. Without 
                                                                //mentioning the default value, it will 
                                                                //return a nil value.        

Transforming values:

The map()?method has a risk of creating duplicate keys. So we can use mapValues() method. It transforms each value inside a dictionary, putting the transformed result into a new dictionary using the original keys. This gives us the transforming behaviour of?map()?without the risk of duplicate keys.

let scores = ["TKB": 80, "BKB": 90, "DS": 95]

let formatedScore = scores.mapValues { "Score: \($0)" }
print(formatedScore) //["BKB": "Score: 90", "TKB": "Score: 80", "DS": "Score: 95"]        

Grouping sequences:

?Dictionary(grouping: collection), this method converts a sequence into a dictionary based on any grouping user wants.

let names = ["Tarun", "Barun", "Tarok","Briti", "Dipu"]

let alphabetical = Dictionary(grouping: names) { $0.first } // Based of first letter.

//Output: [Optional("B"): ["Barun", "Briti"], Optional("T"): ["Tarun", "Tarok"], Optional("D"): ["Dipu"]]

let length = Dictionary(grouping: names) { $0.count } // Based on letter count

// Output: [5: ["Tarun", "Barun", "Tarok", "Briti"], 4: ["Dipu"]]        

Filtering data:

This would filter the exam results dictionary so that it includes only those who scored over 80.

let scores = ["TKB": 79, "BKB": 90, "DS": 95]

let letterMarks = scores.filter { key, value in
    return value >= 80
}

// Output: ["BKB": 90, "DS": 95]
        


Thank you!!

要查看或添加评论,请登录

Tarun Kumar Biswas的更多文章

社区洞察

其他会员也浏览了