回顾:经过验证的批处理
Coddy 面向 C# 开发者的 Swift 课程的第 36 课,共 48 课。
挑战
简单实现 BatchError: Error,包含 case negative。在 Functions.swift 中实现 checkedTotal(_ values: [Int]) -> Result<Int, BatchError>:如果任一值为负数,则失败;否则返回总和(输入为空时总和为零)。输入包含 0 到 50 个介于 -100 到 100 之间的整数。输出总和或 negative。
实现所需的 API 和 solve(_ input: String) -> String。返回不带末尾换行符的输出文本;不要在可编辑代码中打印。锁定的驱动程序会使用其他有效输入独立检查这些 API,然后将返回的文本打印出来,并且只添加一个换行符。所有数值运算都在 Int 的范围内。
你的代码写在 BatchError.swift 和 Functions.swift 中。main.swift 包含提供的输入/输出代码,不能编辑。
亲手试试
import Foundation
func apiChecks(_ input: String) -> Bool {
guard case .success(8) = checkedTotal([3,5]), case .failure(.negative) = checkedTotal([2,-1]), case .success(0) = checkedTotal([]) else { return false }; return true
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 开始公共 API 检查
let apiOK = apiChecks(input)
// 结束公共 API 检查
if apiOK { print(solve(input)) } else { print("API mismatch") }
面向 C# 开发者的 Swift中的所有课
自己练习: Swift 在线编辑器