1. Random Number Generating

Before Swift 4.2

//Generating random number between 0 and 5 before swift 4.2
let oldRandom = Int(arc4random_uniform(5))

After Swift 4.2

let newRandom = Int.random(in: 0..5)
let floatRandom = Float.random(in: 0..<5)
let boolRandom = Bool.random() // no need to specify range

2. CaseIterable For Enums

Enumeration is powerful side of Swift that provides to write code in safe. Sometimes, we need to reach all items of enums or specific item at index. Swift 4.2 brings new protocol named Case Iterable that provides to reach all Cases.

Before Swift 4.2

enum Languages: String { 
    case Swift
    case C 
    case Java
    
    static let allItems: [Languages] = [.Swift, .C, .Java]
}
for item in Languages.allItems {
   print(item) // prints the all cases in our enum
}

You can see that we created an static variable that holds all cases. Now, we don’t need to do that anymore. We can directly reach the all cases with implementing the CaseIterable protocol :

After Swift 4.2

enum Languages: String, CaseIterable { 
    case Swift
    case C 
    case Java
}
for item in Languages.allCases {
   print(item)
}

Also, we can reach the item in specific index as shown:

if Languages.allCases[0].rawValue == "Swift" {
   print("First case is Swift")
}

3. Toggle For Booleans

Swift 4.2 brings us new method to change value of a boolean.

Before Swift 4.2

var isSelectedItem = true
isSelectedItem = !isSelectedItem

After Swift 4.2

isSelectedItem.toggle() // makes it opposite

4. All Satisfy

allSatisfythat check every item of an collection or array for specific condition that you want and returns a boolean value :

let numbers = [1,2,3,4,5,6]
let isAllNumbersEven = numbers.allSatisfy{ (number) -> Bool in 
    return number % 2 == 0
}

Advertisements