Search Your Question

Showing posts with label Collections. Show all posts
Showing posts with label Collections. Show all posts

Explain collections in Swift

Following are different types of collections in Swift:

Array
Set
Dictionary

Let's understand one by one : 

1. Array

  • Most common and Widely used data type. 
  • Ordered collection of similar types of data. 

Declaration: 

var normalArray = [Int]() // declaring an empty                        Int array like this

  • The array can be any type in swift. 
  • We can also declare with some initial values. 
  • Swift is a strongly typed language so we don’t have to tell the type when we declare an array but we can also specify the type

var normalArray = [2,3,4,5]
var normalArray: [Int] = [2,3,4,5]

You also can declare an array with some repeated values or using one or more arrays

var normalArray = Array(repeating: 1, count: 3) //initialize normalArray with three ones var normalArray = arrayOne + arrayTwo //initialize normalArray with addign arrayOne & arrayTwo
  • Insert elements into an Array: We can insert an element at the end of the array or in a valid position.
normalArray.append(12) //append element at the end of array
normalArray += [100.0] //append at the end
normalArray.insert(12, at: 0) //insert element at 0 position. This position value should be n to n-1 if array have n number of elements.
  • Access Elements of Array: We can access the element of an array using a subscript syntax, passing the index value into it. Also swift provided a list of methods to get values and check different parameters.
normalArray[2]  //return second element from array
normalArray.count // return the number of elements in array
normalArray.isEmpty // return false if array is empty
normalArray.capacity // return the number of elements in array
normalArray.first //get the first element from array
normalArray.last //get the last elements from array
normalArray.max() //get the max element from array
normalArray.min() //get the min element from array
normalArray.sorted() // sort the array
normalArray.reversed() //reverse an array
normalArray.shuffled() //shuffle the elements of an array
  • Replace elements of Array: Array value can set or replace in a specific index or for a range of the index.
normalArray[2] = 1 // replace the value in second index of arraynormalArray[1...3] = [12, 23, 34] // set first to third position value as 12, 23 &34
  • Remove elements from Array: Array elements can remove from different ways & different positions.
normalArray.removeAll() // remove allelement from array
normalArray.removeFirst() // remove first element from array
normalArray.removeLast() // remove last element from array
normalArray.remove(at: 2) //remove second element from arraynormalArray.removeLast(1) // remove the second element from the end index of arraynormalArray.removeFirst(2) // remove the thirdelement from the start index of the array
  • Iterate over the array: Every element of an array can be traverse using loop
for i in 0..<normalArray.count{
print(normalArray[i])
}
or
for item in normalArray{
print(item)
}

2. Dictionary

  • Can hold multiple unordered data in key-value pairs. 
  • Each value is associated with a unique key and any value from the dictionary can access with the associated key with it.

  • Declaration: 
var normalDictionary = [Int: String]() 
// an empty "normalDictionary" with Int type key & String type value

  • The key-value pair of a dictionary can be any type in swift. 
  • We can also declare with some initial values. 
  • Swift is a strongly typed language so we don’t have to tell the type of key-value pair when we declare a dictionary but we can also specify the type

var normalDictionary = [1: "John", 2: "Doe"]
var normalDictionary : [Int: String] = [1: "John", 2: "Doe"]
  • Insert elements into a Dictionary: We can insert a value into the dictionary using a key. If the key already exists it will replace the previous value for this key elsewhere it will add a new value.
normalDictionary[3] = "Mihalos"  // Add a value "Mihalos" for key "3"
  • Access Elements of Dictionary: We can access the elements of a dictionary by using the key. Also swift provided a list of methods to get values and check different parameters.
normalDictionary[2] //return the value of second key-value pair in dictionary normalDictionary.count // return the number of elements in dictionarynormalDictionary.isEmpty  // return false if dictionary is emptynormalDictionary.capacity  // return the number of elements in dictionarynormalDictionary.first  //get the first element from dictionarynormalDictionary.max { a, b in a.value < b.value}  // return key-value pair for maximum valuenormalDictionary.min()  { a, b in a.value < b.value}  // return key-value pair for minimumvaluenormalDictionary.sorted( by: { $0.0 < $1.0 }) // reurn an sorted array of dictionarynormalDictionary.reversed()  //return key-value pair in reverse ordernormalDictionary.shuffled()  //shuffle the key-value pair of dictionary
  • Replace elements from a Dictionary: A value for a key is simply replaced by putting a new value for that key. We also can use “updateValue” method to replace the value for any key. But Remember “updateValue” method returns the previous value as output.
normalDictionary[3] = "Mike"
normalDictionary.updateValue("Duke", forKey: 3)
  • Remove elements from Dictionary: Dictionary elements can be removed in a different way.
normalDictionary[3] = nil  // remove key-value pair for key "3"
normalDictionary.removeAll() // remove all element from dictionary arraysimpleDictionary.removeAll(keepingCapacity: true) remove all elements with keeping the capacity or not
  • Iterate over the Dictionary: Every key-value pairs of a dictionary can be traverse using loop
for (key, value) in normalDictionary {
print(key, value)
}

Instead of key-value pair we also can access only key or value from dictionary like this

for key in normalDictionary.keys{
print(key)
}
for value in normalDictionary.values{
print(value)
}

We also can get the keys and values of a dictionary as an array.

let keys = [Int](normalDictionary.keys)  // return all the keys as an array
let values = [String](normalDictionary.values) //return all the values as an array

3. Set

  • Set is an unordered collection of the same type of data. 
  • The main characteristic of the set is, set can not have any duplicate elements.

  • Declaration: You can declare an empty Int type set like this
var normalSet = Set<Int>() // an empty Int type set

  • The set can be any type in swift. 
  • We can also declare with some initial values. 
  • Swift is a strongly typed language so we don’t have to tell the type when we declare a set but we can also specify the type

var normalSet = Set([10, 20, 30, 40, 20])
varnormalSet: Set<String> = ["John", "Doe", "Hi", "John"]

You also can declare a set with some repeated values but you will get a single value for those repeated value cause set didn’t store any duplicate element.

var normalSet = Set(repeatElement(1, count: 3)) // Initialize set with three ones but set will have only one into it.
  • Insert elements into a set: We can insert an element at the end of the array or in a valid position.
normalSet.insert(12) // //append element at the end of set
  • Access Elements of a set: Like array you cannot access set elements using subscript syntax but you can check an element is in the set or not. Also swift provided a list of methods to get values and check different parameters.
normalSet.contains(2)  // check an element is in the set or not
normalSet.count // return the number of elements in set
normalSet.isEmpty // return false if set is 
empty normalSet.capacity   // return the number of elements in setnormalSet.first //get the first element from set
normalSet.max() //get the max element from set
normalSet.min() //get the min element from set
normalSet.sorted() // sort the set
normalSet.reversed() // reverse set
normalSet.shuffled() // shuffle set elements
  • Remove elements: Set elements can remove from different way & from different positions also.
normalSet.removeFirst() // remove first element from set
normalSet.remove(1) // remove from a specific index
normalSet.removeAll() // remove all elements from set
normalSet.removeAll(keepingCapacity: true) // remove all elements with keeping the capacity or not
  • Iterate over the set: Every element of a set can be traverse using loop
for data in normalSet {
print(data)
}

The set type didn’t have any order so if you want to traverse in any order you can do it by swift provided methods

for data in normalSet.sorted() {
print(data)
}
for data in normalSet.reversed() {
print(data)
}
  • Different set operations: You also can perform different set operations within two sets and each of those operations will create a new set.
normalSet2.union(normalSet3).sorted()  // perform union opertion within normalSet2 & normalSet3
normalSet2.intersection(normalSet3) // perform intersection within two set
normalSet2.subtracting(normalSet3) // perform subtracting
normalSet2.symmetricDifference(normalSet3) // perform symmetricDifference
normalSet2.isSubset(of: normalSet3) // check one set is subset of snother or not
normalSet2.isSuperset(of: normalSet3) // check superset or not
normalSet2.isDisjoint(with: normalSet3) // check disjoint or not

There are some more interview questions answers for collections in this site. Visit here

Difference between mutable array and immutable array?

Ans : 

Mutable Array content can be changed but Immutable Array content can not be changed.

You can insert, update, remove item from Mutable Array, but same is not possible in Immutable Array. There is no any methods like RemoveItem or ReplaceItem for Immutable Array, which are available for Mutable Array.

So in Immutable Array, content can not be changed after initialisation. It is either be initialised by content or by nil.

Use of Immutable array 

1. Used when we want to give array to other coder who can't be change array content.
2. Used when only fixed contents are there like array of months, days which can't be changed.

Write program for ascending sorting Int Array in any language

Ans : 
(Interviewer told syntax doesn't matter, write pseudo-code type program)

1. Not using direct function.

 void main()
    {

        int i, j, a, n, number[30];
        printf("Enter the value of N \n");
        scanf("%d", &n);

        printf("Enter the numbers \n");
        for (i = 0; i < n; ++i)
            scanf("%d", &number[i]);

        for (i = 0; i < n; ++i)
        {

            for (j = i + 1; j < n; ++j)
            {

                if (number[i] > number[j])
                {

                    a =  number[i];
                    number[i] = number[j];
                    number[j] = a;

                }

            }

        }

        printf("The numbers arranged in ascending order are given below \n");
        for (i = 0; i < n; ++i)
            printf("%d\n", number[i]);

    }

2. If we write in swift using higher order function, then

var numbers = [45,6,113,56,8,56,43,78]

print(numbers.sort()) //Sorting in Ascending order

print(numbers.sort(>)) //Sorting in Descending order

Interviewer mostly asked this question to check your programming logic. So he/she don't require syntax.

Q. Sorting strings array
A.
Method 1 : 
var sortedArray = swiftArray.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }

Method 2 : 
let sortedNames = names.sort { $0.name < $1.name }
let sortedNames = names.sorted(by: <)


Difference between Swift Array and Objective C Array

Ans : Swift arrays (Array and for short, []) are passed by value which means
that every object contained will be copied.

NSArray are implemented as classes (and bridged from ObjC) so they're passed as references.

In Swift, we can declare three type of array.
One is Array or [],
Second is NSArray,
Third is NSMutableArray.

NSArray and NSMutableArray are coming from Objective C by bridge. So interviewer may ask what are difference between types arrays in swift?

Extract value from Array : 

Get 3rd Value from Array

Objective C : [arr objectAtIndex:2] // 2 due to index start from 0 in array

Swift : arr[2] 

Why array method containObject has id as parameter in ios?

Ans : id is a generic type. This means that the compiler will expect any object type there, and will not enforce restrictions. It can be useful if you're expecting to use more than one class of objects there. So you can add anything of type id to an NSArray.

So array method containObject has id type as parameter.

- (BOOL)containsObject:(ObjectType)anObject;

Usage :

bool bVal = [arr containObject:@5];

How to take common elements from two array in ios?

Ans. 

Swift higher order function is very useful. See below example.


let fruitsArray = ["apple", "mango", "blueberry", "orange"]
let vegArray = ["tomato", "potato", "mango", "blueberry"]

// only Swift 1
let output = fruitsArray.filter{ contains(vegArray, $0) }

// in Swift 2 and above
let output = fruitsArray.filter{ vegArray.contains($0) }
// or
let output = fruitsArray.filter(vegArray.contains)


Array vs Set

let array1: Array = ...
let array2: Array = ...

// Array
let commonElements = array1.filter(array2.contains)

// vs Set
let commonElements = Array(Set(array1).intersection(Set(array2)))

// or (performance wise equivalent)

let commonElements: Array = Set(array1).filter(Set(array2).contains)

Another way in Swift 4.0

   var someHash: [String: Bool] = [:]

   fruitsArray.forEach { someHash[$0] = true }

   var commonItems = [String]()

   vegArray.forEach { veg in
    if someHash[veg] ?? false {
        commonItems.append(veg)
    }
   }


   print(commonItems)



What are higher order functinos in swift?

Ans : Higher order functions are functions that operate on other functions by taking function as argument or returning function.

 Sorted : Sorting array. It may takes closure as argument and returns array .
let numbers : [Int] =  [1,5,2,4,3]
let arrNumbers = numbers.sorted()

By default it returns in ascending order.

numbers.sorted(by: (Int,Int) -> Bool)  - > How we want to sort array then sorted(by:)
numbers.sorted((a,b) -> Bool in return a > b } // descending order
numbers.sorted(by : >)

      Map : It iterates through the array that is calling it and changes each element of the array based on the closure passes to the method.

Use map to loop over a collection and apply the same

operation to each element in the collection. It returns after

applying transform.

let arrInt = [1,8,4,6]
I want add 1 in every number in array.
Without loop, using map,

arrInt.map( $0 + 1)  // <- This is shortest code for doing map

output : [2,9,5,7]

How map works :

The map function has a single argument which is a closure (a

function) that it calls as it loops over the collection. This

closure takes the element from the collection as an argument and

returns a result. The map function returns these results in an

array.

Another example :

let chocolateAmt = [“Dairy Milk”:20.0, “Munch”:10]

I want to increase price 5%,
so using map,
chocolateAmt.map{ (key, value) in
   value + value*0.05
      }

output : [“Dairy Milk”:21.0, “Munch”:10.5]

Another Example :

If we want index in map,

let arrInt = [1, 2, 4, 5]
let indexElement = arrInt.enumerated().map { (index,element) in
return "\(index):\(element)"
}
print(indexElement) // [“0:1”, “1:2”, “2:4”, “3:5”]

CompactMap: Use this method to receive an array of nonoptional values when your transformation produces an optional value.

let scores = ["1", "2", "three", "four", "5"]

let mapped: [Int?] = scores.map { str in Int(str) }
// [1, 2, nil, nil, 5] - Two nil values as "three" and "four" are strings.

let compactMapped: [Int] = scores.compactMap { str in Int(str) }
// [1, 2, 5] - The nil values for "three" and "four" are filtered out. 


FlatMapFlatmap is used to flatten a collection of collections.

Flatmap is joined word of Flat + Map. So as per name, it applies map function over collection and do flatten collection.


Test 1 :

let codes = [["abc","def","ghi"],["jkl","mno","pqr"]]
let newCodes = codes.flatMap { $0.map {$0.uppercased()} }
print(newCodes)


Output : ["ABC","DEF","GHI","JKL","MNO","PQR"] 


Test 2 :

let codes = ["abc","def","ghi"]
let newCodes = codes.flatMap { $0.uppercased() }
print(newCodes)

Output : ["A","B","C","D","E","F","G","H","I"]

-> In Test 2, first it applies map so half output is like 

["ABC","DEF","GHI"] and after that it applies flat so now full 

output is : ["A","B","C","D","E","F","G","H","I"]


Tip : 

1. String is collection from Swift 4.

2.If you do flatmap a collection containing optional values, 

flatmap will only consider the non-nil values.

let codes = [1,2,nil,3,nil,5]

let newCodesFlatMap = codes.flatMap { return $0 }
output : [1,2,3,5]


let newCodesFlatMap = codes.map { return $0 }

output : [optional(1),optional(2),nil,optional(3),nil,optional(5)]


The output of map became a collection of optional int ([Int?]) 



only because the array had nil — value in it. Otherwise it would 



have been an Int array. It is benefit of using flatMap.



Filter : Return array with elements which fulfill filter condition.           
let numbersLessThanFive = numbers.filter { (a) -> bool in return a  <  5 }
let numbersLessThanFive = numbers.filter { $0 < 5}

          Reduce : It is used to combine all element in array to make one single value.
let sumOfNumbers = numbers.reduce(0, { $0 + $1 }) 

Difference between map and flatmap : 

Big difference is Map considers nil but flatmap  remove nil value from collection.