复习:验证批次
Coddy 面向 Luau 开发者的 Swift 课程 课程的第 36 课,共 48 课。
挑战
简单实现包含 negative case 的 BatchError: Error。在 Functions.swift 中实现 checkedTotal(_ values: [Int]) -> Result<Int, BatchError>:如果任何值为负数,则失败;否则成功返回总和(对于空输入,总和为 0)。输入包含 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") }
面向 Luau 开发者的 Swift 课程中的所有课
自己练习: Swift 在线编辑器