Bindings and Mutation
Lesson 2 of 48 in Coddy's Swift for R Developers course.
R names bind to objects, and an ordinary binding can later hold a different type. Rebinding label does not change saved. Most ordinary vectors and lists have copy-on-modify behavior, while environments have reference semantics; neither a name nor the assignment arrow alone specifies an immutable domain value.
Swift infers a static type from an initializer. let prevents reassignment and var permits mutation within that type. A String has value semantics: changing a mutable copy preserves the original value. A declaration with var does not allow the variable to change from String to Int.
The R local changes from a character vector to a number, while the Swift variable remains a String. These examples separate reassignment from mutation of a shared object. Choose the target type and its mutability independently.
Complete R comparison program:
label <- "draft"
saved <- label
label <- 17
cat(saved, label, sep = " ")
cat("\n")
Complete Swift comparison program, compiled from these files:
main.swift
let saved = "draft"
var label = saved
label = "ready"
print(saved, label)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 R 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