If and Branch Values
Lesson 9 of 48 in Coddy's Swift for Luau Developers course.
Luau has if-then-else expressions that choose one value directly. Unlike the older and/or selection idiom, this expression can return false or nil from its true branch without falling through to the alternative. Conditions still follow Luau truthiness, where zero and empty text are true.
Swift also allows if expressions, with compatible branch result types and a Bool condition. Its braces differ from Luau's expression syntax. The ternary operator is another choice. Here saved is a Boolean in both programs, so the unsaved branch yields editing without relying on truthiness conversion.
Luau
Complete Luau console program:
main.luau
local saved = false
local caption = if saved then "synced" else "editing"
print(caption)
Swift
Complete program; compile the listed files together:
main.swift
import Foundation
let saved = false
let caption = if saved { "synced" } else { "editing" }
print(caption)Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Luau 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