Menu
CoddyTech

Recap: Value Basket

Lesson 30 of 48 in Coddy's Swift for Dart Developers course.

challenge icon

Challenge

Easy

Implement value types Item(name:price:) with immutable String name and Int price, and Basket() with add(_ item: Item), computed total: Int, and count: Int. A copied basket must be independent. Input is 0 through 30 nonnegative prices, each at most 1000. Add one item per price to a basket, copy it, add a price-1 item to the copy, and output original total, copy total, and original count.

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 Item.swift, Basket.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 {
var b = Basket(); b.add(Item(name: "x", price: 7)); var c = b; c.add(Item(name: "y", price: 4)); return b.total == 7 && c.total == 11 && b.count == 1 && c.count == 2
}
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 Dart Developers

Practice on your own: Swift playground