Read a telescope setting
Before you start this intermediate track
Functions and collections. Work with structs, mutable bindings, and optionals.
Guided code reading and debugging. Runnable coding challenges are available in JavaScript, Python, and SQL.
Understand it, then try it.
A telescope receives a magnification setting as text. Int returns an optional because not every string is a valid integer. Optional binding with if let safely extracts a successful conversion. Inside that branch, magnification is an ordinary integer that can be doubled; the else branch handles an invalid setting.
let reading = "40"if let magnification = Int(reading) { print("Zoom: \(magnification * 2)x")} else { print("Invalid setting")}Run each mission independently as a Swift 5.9 or later script or playground. Top-level statements execute directly; these examples need only the Swift standard library and no Apple UI frameworks.
Track the values line by line. Predict the result before running this example in your own editor.