Swift - 使用闭包来查找给定代码的两个数字之和的代码

时间:2018-05-16 05:26:37

标签: swift closures

//使用两个Int numbers(num1 and num2)编写程序并返回这些数字的总和//

给定和禁用代码:

import Foundation//given and disabled

// Write your code here.(I have to write my code here so that it gives 10 is 5 5 is given as input at run time)

 //my code 
let closure: (Int,Int) -> (Int) = {
return $0 + $1
}

//below code is given code and disabled.

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 = let closure(number1: number1, number2: number2)

fileHandle.write(String(res).data(using: .utf8)!)

fileHandle.write("\n".data(using: .utf8)!)

现在当我编写代码时,它会在禁用代码中出现编译错误。请帮忙。

1 个答案:

答案 0 :(得分:1)

你应该使用这样的闭包,

let res = closure(number1, number2)