回顾:预订账本
Coddy 面向 Ruby 开发者的 Swift 课程的第 42 课,共 48 课。
挑战
简单实现引用类型 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") }
面向 Ruby 开发者的 Swift中的所有课
自己练习: Swift 在线编辑器