Menu
CoddyTech

Bindings and Mutation

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

Ruby local variables can be rebound to objects of different types. Reassigning label to an integer does not change saved. Ruby String objects can be mutable, so replacing a binding and mutating a shared string object are separate operations; this example only replaces the binding.

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 Ruby local becomes an Integer while the Swift local stays a String. Swift lets you choose mutability independently from its fixed static type. Later examples distinguish mutable source objects from target value semantics, rather than treating every reassignment as shared mutation.

Complete Ruby comparison program:

label = "draft"
saved = label
label = 17
puts "#{saved} #{label}"

Complete Swift comparison program, compiled from these files:

main.swift

let saved = "draft"
var label = saved
label = "ready"
print(saved, label)
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 Ruby Developers

Practice on your own: Swift playground