Swift : Program for addition of 2 numbers using closure

后端 未结 2 1996
栀梦
栀梦 2021-01-27 06:36
let fileName = ProcessInfo.processInfo.environment[\"OUTPUT_PATH\"]!
FileManager.default.createFile(atPath: fileName, contents: nil, attributes: nil)
let fileHandle = Fi         


        
2条回答
  •  失恋的感觉
    2021-01-27 07:07

    Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.

    Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.

    Reference: click here

    Example:

    For sorting you can define a simple function, and to pass it in as an argument to the sorted(by:) method:

    let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
    
    func backward(_ s1: String, _ s2: String) -> Bool {
        return s1 > s2
    }
    
    var reversedNames = names.sorted(by: backward)
    // reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
    

    Rather than using a function you can write closure for that, as:

    var reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
        return s1 > s2
    })
    

    Solution for your problem:

    Either you write and use:

    func closure(number1: Int, number2: Int) {
        return number1 + number2
    }
    
    let res = closure(number1: number1, number2: number2)
    

    Or, you can implement:

    let closure:((Int, Int) -> Int) = { (number1, number2) in return number1 + number2 }
    
    let res = closure(number1: number1, number2: number2)
    

提交回复
热议问题