Menu
CoddyTech

复习:预订账本

Coddy 面向 Java 开发者的 Swift 课程的第 42 课,共 48 课。

challenge icon

挑战

简单

实现引用类型 BookingLedger(capacity:),其中 used 为只读属性,初始值为零,并实现 reserve(_ count: Int) -> Bool。只接受大于零且不超过剩余容量的数量,将 used 更新一次,并返回 true。拒绝请求时状态保持不变。输入为容量(0 到 100),随后是 0 到 30 个请求(-10 到 100)。输出已使用容量和已接受的请求数量,两者之间用空格分隔。

实现所需的 API 和 solve(_ input: String) -> String。返回不带末尾换行符的输出文本;不要在可编辑代码中打印。锁定的驱动程序会使用其他有效输入独立检查这些 API,然后将返回的文本连同且仅连同一个换行符打印出来。所有数值运算都在 Int 的范围内。

你的代码写在 BookingLedger.swift 和 Functions.swift 中。main.swift 包含提供的输入/输出代码,不能编辑。

亲手试试

import Foundation
func apiChecks(_ input: String) -> Bool {
let x = BookingLedger(capacity: 9); guard x.reserve(4) && !x.reserve(6) && !x.reserve(0) && x.used == 4 else { return false }; return x.reserve(5) && x.used == 9 && !x.reserve(1)
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 开始公开 API 检查
let apiOK = apiChecks(input)
// 结束公开 API 检查
if apiOK { print(solve(input)) } else { print("API mismatch") }

面向 Java 开发者的 Swift中的所有课

自己练习: Swift 在线编辑器