Bindings and Mutation
Lesson 2 of 48 in Coddy's Swift for Java Developers course.
Java final prevents reassignment of a variable. If it holds an object reference, the object can still be mutable. Swift let also fixes a binding, but a value stored in a let binding cannot be mutated. Use var for a binding whose value changes.
The examples replace a saved temperature with a new measurement. Java local type inference uses var; Swift usually infers a type after either let or var. Neither inference makes the variable dynamically typed. Swift writes an explicit type after the name, as in var reading: Int.
Java: complete program
Main.java
import java.util.*;
import java.util.function.*;
public class Main {
public static void main(String[] args) throws Exception {
final int saved = 18;
int current = saved;
current = 21;
System.out.println(saved + " " + current);
}
}Swift: complete program
main.swift
import Foundation
let saved = 18
var current = saved
current = 21
print("\(saved) \(current)")A Java final ArrayList may still accept elements. A Swift let array cannot use mutating array operations. Later lessons distinguish that value behavior from a let reference to a mutable class.
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 Java 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