Menu
CoddyTech

Bindings and Mutation

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

C const qualifies an object or the type accessed through a pointer; it does not generally freeze all reachable data. A const pointer and a pointer to const describe different restrictions. Swift let fixes a binding, while var permits the value to change. A value-type instance bound with let cannot be mutated.

The programs preserve a saved temperature and replace an independent current reading. C normally writes a declared type before the local name, while Swift can infer its type or write it after a colon. In either case a mutable scalar binding retains its type; mutation is not dynamic typing.

C: complete program

main.c

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

int main(void) {
const int saved = 18;
    int current = saved;
    current = 21;
    printf("%d %d\n", saved, current);
    return 0;
}

Swift: complete program

main.swift

import Foundation
let saved = 18
var current = saved
current = 21
print("\(saved) \(current)")

A Swift let class reference can still refer to mutable instance state. Separate binding restrictions from the representation of the referenced data.

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