Wednesday, 31 July 2019

Tuples, for-in, Dictionary Grouping, Filtering and Set



Set’s: 
sets are used to store distinct values of same types but they don’t have definite ordering as arrays have.(sets allow only distinct values.)

var someSet = Set<Character>()     //Character can be replaced by data type of set.

Set Operations
  • Intersection
  • Union
  • subtracting
let evens: Set = [10,12,14,16,18]
let odds: Set = [5,7,9,11,13]
let primes = [2,3,5,7]
odds.union(evens).sorted()
// [5,7,9,10,11,12,13,14,16,18]
odds.intersection(evens).sorted()
//[]
odds.subtracting(primes).sorted()
//[9, 11, 13]

Dictionary’s : 

var cities = [“Delhi”,”Bangalore”,”Hyderabad”]
var Distance = [2000,10, 620]

let cityDistanceDict = Dictionary(uniqueKeysWithValues: zip(cities, Distance))

Filtering
var closeCities = cityDistanceDict.filter { $0.value < 1000 } //Output : ["Bangalore" : 10 , "Hyderabad" : 620]


Higher order functions in Swift: Filter, Map, Reduce, flatmap, compactMap : 
higher order functions that can be used on collection types
higher order functions are functions that takes another function/closure as argument and returns it.



Dictionary Grouping

var cities = ["Delhi","Bangalore","Hyderabad","Dehradun","Bihar"]

var GroupedCities = Dictionary(grouping: cities ) { $0.first! }// Output : ["D" :["Delhi","Dehradun"], "B" : ["Bengaluru","Bihar"], "H" : ["Hyderabad"]]


JSON dynamic adding objects:
for a in res2 {
    if let nm = a["nm"] as? String, let uni = a["uni"] {
        self.dic[nm] = uni as? String
    }
}
print(self.dic)

for-in loop :
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]

for (index, keyValue) in someDict.enumerated() {
   print("Dictionary key \(index) - Dictionary value \(keyValue)")
}

Tuples:
which are used to group multiple values in a single compound Value.

The values in a tuple can be of any type, and do not need to be of same type.
For example, ("Tutorials Point", 123)

Good link : https://medium.com/@abhimuralidharan/tuple-in-swift-a9ddeb314c79

EX:

Ex1)(“tuple", 1, true) //Tuple with different data types.

Ex2) var person = ("John", "Smith”)//Read values from tuple

var firstName = person.0 // John
var lastName = person.1 // Smith

Ex3)var point = (0, 0) //Assign values to tuple

point.0 = 10
point.1 = 15

point // (10, 15)

Note: Tuple are value types. When you initialize a variable tuple with another one it will actually create a copy.
var origin = (x: 0, y: 0)

var point = origin
point.x = 3
point.y = 5

print(origin) // (0, 0)

print(point) // (3, 5)


No comments:

Post a Comment

Difference between == and ===

Difference between == and === https://stackoverflow.com/questions/24002819/difference-between-and == operator checks if their ...