Swift : Program for addition of 2 numbers using closure

后端 未结 2 1998
栀梦
栀梦 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:29

    Closures are really simple in Swift. Here is an example Closure for adding two numbers:

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

    Just like with normal variables you set the type of a closure after a colon. In this case it's:

    ((Int, Int) -> Int)
    

    which means: Take two Ints as parameters and return a Int.

    Usage:

    let firstNumber = 5
    let secondNumber = 6
    
    let additionResult = closure(firstNumber, secondNumber)
    //additionResult is 11
    

    In your specific use case:

    let closure:((Int, Int) -> Int) = { (number1, number2) in
        return number1 + number2
    }
    
    let fileName = ProcessInfo.processInfo.environment["OUTPUT_PATH"]!
    FileManager.default.createFile(atPath: fileName, contents: nil, attributes: nil)
    let fileHandle = FileHandle(forWritingAtPath: fileName)!
    
    guard let number1 = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
    else { fatalError("Bad input") }
    
    guard let number2 = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!)
    else { fatalError("Bad input") }
    
    let res = closure(number1, number2)
    
    fileHandle.write(String(res).data(using: .utf8)!)
    fileHandle.write("\n".data(using: .utf8)!)
    

提交回复
热议问题