Bindings and Mutation
Lesson 2 of 48 in Coddy's Swift for JavaScript Developers course.
JavaScript const prevents rebinding a local but does not freeze the object it references. Both names here refer to one mutable array, so changing its length is visible through either name. Object.freeze adds a separate shallow runtime restriction and still does not recursively freeze every nested object. Swift let fixes a binding too, but Array is a value type whose elements cannot be changed through a let-bound value.
JavaScript let allows a local to receive values of different types over time. Swift var instead retains its inferred static type. The target clears a var-bound copy while preserving the original array value, so source aliasing and target value copying produce different counts.
JavaScript
Complete JavaScript console program:
main.js
const pending = ["upload", "index"];
const alias = pending;
alias.length = 0;
console.log(pending.length, alias.length);
Swift
Complete program; compile the listed files together:
main.swift
import Foundation
let pending = ["upload", "index"]
var copy = pending
copy.removeAll()
print(pending.count, copy.count)Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for JavaScript 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 RulesPractice on your own: Swift playground