Closures


Ref. Link

https://youtu.be/fVF_tNcIhfc

https://medium.com/swift-india/functional-swift-closures-67459b812d0





import UIKit


class ViewController: UIViewController {


    //This is a closure which doesn't require any parameter and no return type

    var closure_1: () -> Void = {

        print("closure_1 called")

    }

    

    //This is a closure which requires Int as a parameter and no return type

    var closure_2: (Int) -> Void = { intValue in

        print(intValue)

    }

    

    //This is a closure which requires Int as a parameter and returns sq of that number

    var closure_3: (Int) -> Int = { intValue in

        return intValue * intValue

    }

    

    //This closure will add two Int and return new Int

    var addTwoNumbers: (Int, Int) -> Int = { number1, number2 in

        return number1 + number2

    }

    

    

    //This is a trailing closure

    func getDataFromAPI(url: String, completion: (Any?, Error?) -> Void) {

        //Once you receive data from api, call 'completion' closure

        completion("DATA from API", nil)

    }

    

    override func viewDidLoad() {

        super.viewDidLoad()

        

        closure_1() // print: closure_1 called

        closure_2(10) // print: 10

        

        let sqOfNumber = closure_3(4)

        print(sqOfNumber) // print: 16

        

        let additionOfNumber = addTwoNumbers(2, 6)

        print(additionOfNumber) // print: 8

        

        getDataFromAPI(url: "http://anyURL") { (data, error) in

            if let _ = error {

                //if error dont do anything

            }else {

                if let data = data as? String {

                    print(data) // print: DATA from API

                }

            }

        }

    }

}



Comments

Popular posts from this blog

SubString in Swift

PUSH Notification