Menu
CoddyTech

Bindings and Mutation

Lesson 2 of 48 in Coddy's Swift for C++ Developers course.

C++ auto requests type inference and does not itself make a local immutable; const supplies a separate restriction. Swift similarly infers a fixed type but explicitly distinguishes let from var. A C++ const object may be initialized at runtime, while constexpr imposes additional constant-expression rules. Swift let also permits runtime initialization. The examples reassign a string and then preserve a label. C++ pointer constness and pointee constness are distinct, and a const smart pointer can still expose mutable pointee state. Likewise a Swift let class reference does not deeply freeze its instance, while a let-bound struct or String value cannot be mutated.

C++

Complete program file: main.cpp.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>

int main() {
auto mode = std::string("draft");
    mode = "ready";
    const auto label = mode;
    std::cout << label << '\n';
}

Swift

Complete program file: main.swift.

var mode = "draft"
mode = "ready"
let label = mode
print(label)
challenge icon

Challenge

Easy

Implement offset(_ value: Int) -> Int: add 7 to a value. Input is one integer from -1000 through 1000; output is the resulting integer.

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 Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
return offset(31) == 38 && offset(-8) == -1 && offset(31) == 38
}
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 C++ Developers

Practice on your own: Swift playground