Bindings and Mutation
Lesson 2 of 48 in Coddy's Swift for Go Developers course.
Go const declares a compile-time constant, while a Swift let binding may receive a runtime value and then cannot be reassigned. Go := infers a local variable type without making it immutable. Swift chooses inference separately from let or var mutability.
Both programs preserve the saved temperature while changing current. Go variables and Swift bindings retain static types after inference. A Go pointer variable can be reassigned while its pointee has a separate lifetime and mutation contract; a Swift let class reference likewise does not freeze all reachable state.
Go: complete program
main.go
package main
import (
"fmt"
)
func main() {
const saved = 18
current := saved
current = 21
fmt.Println(saved, current)
}
Swift: complete program
main.swift
import Foundation
let saved = 18
var current = saved
current = 21
print("\(saved) \(current)")A Swift let Array value cannot be mutated through that binding. Treat value-type immutability separately from a constant reference to a mutable class instance.
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 Go 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