Structs and Independent Copies
Lesson 26 of 48 in Coddy's Swift for C# Developers course.
C# structs and Swift structs are value types. Assignment copies the value, but reference-valued fields can still refer to shared objects. Neither language promises a recursive deep copy. In this example, changing a copied label affects only that struct, while changing the object stored in both copies is visible through both. Swift methods that mutate a struct require mutating; C# uses no corresponding method modifier. A Swift let binding forbids mutation of the struct value, but it does not make an object referenced by a field immutable. Decide which fields should own values and which intentionally share identities before translating a class-heavy model.
C#
Complete program file: Program.cs.
using System;
using System.Collections.Generic;
using System.Linq;
class Cell { public string Text; }
struct LabelledBox { public string Label; public Cell Shared; }
class Program
{
static void Main()
{
var original = new LabelledBox { Label = "old", Shared = new Cell { Text = "one" } };
var copy = original;
copy.Label = "new";
copy.Shared.Text = "two";
Console.WriteLine(original.Label + " " + original.Shared.Text);
}
}Swift
Complete program file: Cell.swift.
final class Cell { var text: String; init(text: String) { self.text = text } }Complete program file: LabelledBox.swift.
struct LabelledBox { var label: String; var shared: Cell }Complete program file: main.swift.
let original = LabelledBox(label: "old", shared: Cell(text: "one"))
var copy = original
copy.label = "new"
copy.shared.text = "two"
print("\(original.label) \(original.shared.text)")Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for C# 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