Menu
CoddyTech

If and Branch Values

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

R if is an expression and returns the selected branch's result. It requires one usable condition, unlike ifelse, which is designed for vectorized selection and has its own coercion and attribute behavior. Choose the scalar form when the program makes one control-flow decision.

Swift supports if expressions whose branches produce compatible values, and the ternary condition ? first : second form is another choice. The condition must be Bool. Both choices evaluate the selected branch; a false result value does not accidentally select the other branch.

Both scalar examples choose a mode and then a numeric flag. Swift's if expression also produces a value, but its condition must be Bool and branch types must be compatible. Do not substitute a whole logical vector where one target decision is required.

Complete R comparison program:

dark <- TRUE
mode <- if (dark) "night" else "day"
cat(mode, "\n", if (mode == "night") 1L else 0L, "\n", sep = "")

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 R Developers

Practice on your own: Swift playground