Menu
CoddyTech

Bindings and Mutation

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

A Dart final variable is assigned once, but the object it names can still change. A const list is a compile-time constant and cannot be mutated. Swift let also fixes a binding, but a Swift array is a value: changing its elements requires var. Here a Dart alias shares a growable list, while the Swift assignment produces an independent array value. Swift can share backing storage until mutation without changing that observable rule. Type inference in either language does not make a variable dynamically typed. Choose the binding and the object model separately when porting.

Complete Dart program. Each labelled block is a separate file.

main.dart

void main() {
  final route = ['east'];
  final alias = route;
  alias.clear();
  print(route.length);
}

Complete Swift program. Each labelled block is a separate file.

main.swift

import Foundation
let route = ["east"]
var copy = route
copy.removeAll()
print(route.count, copy.count)
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 Dart Developers

Practice on your own: Swift playground