Menu
CoddyTech

Recap: Validated Batch

Lesson 36 of 48 in Coddy's Swift for Kotlin Developers course.

challenge icon

Challenge

Easy

Implement BatchError: Error with case negative. Implement checkedTotal(_ values: [Int]) -> Result<Int, BatchError> in Functions.swift: fail if any value is negative, otherwise succeed with the sum (including zero for empty input). Input has 0 through 50 integers -100 through 100. Output the total or negative.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in BatchError.swift, Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

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)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }

All lessons in Swift for Kotlin Developers

Practice on your own: Swift playground