Menu
CoddyTech

If and Branch Values

Lesson 9 of 48 in Coddy's Swift for GDScript Developers course.

GDScript places a conditional expression value before if, while Swift offers the ternary operator and suitable if expressions. A Swift value-producing branch must supply a compatible result type. An ordinary statement-style if remains useful when several actions belong to a branch.

Swift requires Bool conditions and braces around branch bodies. An else-if chain selects the first matching branch rather than running every later condition. Choose conditions in a deliberate order for overlapping ranges and boundary values, rather than relying on incidental input examples.

The programs select a display mode and derive a small status number. They illustrate branch values; the exercise applies the same control structure to its own charge boundaries.

Complete GDScript comparison program:

extends SceneTree

func _init():
    var dark = true
    var mode = "night" if dark else "day"
    print(mode)
    print(1 if mode == "night" else 0)
    quit()

Complete Swift comparison program, compiled from these files:

main.swift

let dark = true
let mode = if dark { "night" } else { "day" }
print(mode)
print(mode == "night" ? 1 : 0)
challenge icon

Challenge

Easy

Implement shipping(_:) for integer weight 1 through 100. Weights up to 2 cost 4; 3 through 5 cost 7; each unit above 5 adds 2. Output the fee.

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 shipping(2) == 4 && shipping(5) == 7 && shipping(12) == 21
}
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 GDScript Developers

Practice on your own: Swift playground