Menu
CoddyTech

Structs and Independent Copies

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

Dart user-defined class instances have reference semantics, including classes used to represent data. Assigning one to a second variable does not make a new instance. Swift offers struct for value semantics: assigning a struct copies its value. A method that changes stored struct properties must be marked mutating, and the caller needs a mutable binding. Struct copying is not a recursive clone of class objects stored inside it. The Dart example explicitly copies coordinates, while the Swift assignment supplies that behavior for its integer fields.

Complete Dart program. Each labelled block is a separate file.

Position.dart

class Position {
  int x;
  int y;
  Position(this.x, this.y);
  Position copy() => Position(x, y);
  void reflect() { x = -x; }
}

main.dart

import 'Position.dart';
void main() {
  final original = Position(3, 4);
  final copy = original.copy();
  copy.reflect();
  print('${original.x} ${copy.x}');
}

Complete Swift program. Each labelled block is a separate file.

Position.swift

import Foundation
struct Position {
    var x: Int
    var y: Int
    mutating func reflect() { x = -x }
}

main.swift

import Foundation
let original = Position(x: 3, y: 4)
var copy = original
copy.reflect()
print(original.x, copy.x)
challenge icon

Challenge

Easy

Implement value type Score with stored points: Int, init(points:), and mutating award(_ amount: Int) adding amount. Input is initial points and award, each 0 through 1000. Copy the original, award only the copy, and output original and copy points separated by a space.

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 Score.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 {
let original = Score(points: 13); var copy = original; copy.award(6); copy.award(2); return original.points == 13 && copy.points == 21
}
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") }
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Swift for Dart Developers

Practice on your own: Swift playground