Wednesday 12 October 2016

Collection Types in Swift 3.0

Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.
Note*
Swift’s array, set, and dictionary types are implemented as generic collections.

let vs var: 
let:  You can make variable immutable using let keyword.
Note*
It is good practice to create immutable collections in all cases where the collection does not need to change.
var: If you want  to make your variables mutable then you should use var keyword

Collection Types:

  • Array
  • Dictionary
  • Sets
Use the Boolean isEmpty property as a shortcut for checking whether the count property is equal to 0.We can use  isEmpty property with Arrays , Set , Dictionary. 

Array : Arrays are ordered set of collections of values.
Syntax:
To explicitly declare the type of an empty array, wrap the type within square brackets [ ]. You can use either type annotation to set it equal to empty square brackets, or the initializer syntax that uses a parenthesis following the array type:


let arrayItems:[Type] = []      //type annotation.

let arrayItems = [Type]()       // Intializer

 Array with a Default Value:
Swift’s Array type also provides an initializer for creating an array of a certain size with all of its values set to the same default value. You pass this initializer a default value of the appropriate type (called repeating): and the number of times that value is repeated in the new array (called count):

  1. var arrayItems = Array(repeating: 0.0, count: 3)
  2. Output : [0.0 , 0.0, 0.0]
  3. Adding Two Arrays Together:
let firstArray:[Int]  = [1,2,3,4]

let secondArray:[Int] = [5,6,7,8]

let result = firstArray + secondArray

Output: [1, 2, 3, 4, 5, 6, 7, 8]

Subscripting In Array: 

let firstElement = firstArray[0]

Output : 1 

firstArray[1]  = 5      // Error due to let keyword.You can append item to immutable array. Here firstArray is immutable because we are using  let keyword .  

Methods Perform On Arrays
.append()       
.removeLast()  
.popLast()
.reverse()

var firstArray = [1,2,3,4]

append()

arrayItems.append(4)                  // append() is used for adding items in array

removeLast() :Removes and returns the last element of the collection. The collection must not be empty.
firstArray = [1]
firstArray.removeLast()
print(firstArray)                   Output:  []

popLast()Removes and returns the last element of the array.if the array is empty then return nil.

firstArray.popLast() 

print(firstArray)                   Output: [1,2,3,4]

.reverse(): This  method returns a copy of the array with the elements in reverse order. It does not implicitly mutate the array it is called on.

firstArray.reverse()              Output : [4,3,2,1]

ARRAY PROPERTIEs
.first
.last
.count

firstArray.first                               // Return the first element in the array

firstArray.last                               // Return the last element in the array

firstArray.count                           // Return the count of  array


Iteration In Array
for-in  Loop

for item in firstArray {
  print(item)
  
}

SetsA set stores distinct values of the same type in a collection with no defined ordering. You can use a set instead of an array when the order of items is not important, or when you need to ensure that an item only appears once.
Syntax:
The type of a Swift set is written as Set<Element>, where Element is the type that the set is allowed to store. Unlike arrays, sets do not have an equivalent shorthand form.
   
var words = Set<Character>()        //Empty Set 

words = ["a","k","s"]

print(words)                                Output : ["k", "s", "a"]   

 // print in anyorder because set is  unordered collection of unique values


Methods Perform On Sets
.insert()
.remove()
.removeAll()
.removeFirst()


Iteration :

for char in words {
print(char)
}

Set Operations:

















Dictionary:
The type of a Swift dictionary is written in full as Dictionary<Key, Value>, where Key is the type of value that can be used as a dictionary key, and Value is the type of value that the dictionary stores for those keys.
NOTE*
A dictionary Key type must conform to the Hashable protocol, like a set’s value type.
var userDictionary = [String: String]()

var flightsDict: [String: String] = ["US": "Newyork", "AUS": "Australia"]

Use the Boolean isEmpty property as a shortcut for checking whether the count property is equal to 0:

if userDictionary.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary is not empty.")
}

READING A DICTIONARY

Similar to arrays, dictionaries can be subscripted with a key. This syntax returns an optional that will contain nil if the dictionary holds no value for the requested key:

   if let name =  flightDict["name"] {
    print("name ->"\(name))
}

WRITING TO A DICTIONARY

To alter a dictionary by adding a new key-value pair, or overwriting the value of an existing key, the dictionary must be mutable, meaning that it must have been created using var:

var dict: [String: String] = [
"name ": "Rony",
"age" : "27",
"dob" : "08-11-1989"
]

REMOVING FROM A DICTIONARY

dict["name"] = nil

Iteration :

for airportCode in flightsDict.keys {
print("code \(airportCode)")
}

Properties
  • isEmpty
  • count


1 comment: