Recap: Value Basket
Lesson 30 of 48 in Coddy's Swift for Kotlin Developers course.
Challenge
EasyImplement 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 Kotlin Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry Rules3Control Flow
Switch and PatternsEnums as Finite ChoicesFor Loops and RangesWhile and Repeat LoopsRecap: Sequence Scan6Values and References
Structs and Independent CopiesStored and Computed PropertiesClasses and Shared IdentityARC and Weak ReferencesRecap: Value BasketPractice on your own: Swift playground