Menu
CoddyTech

If and Branch Values

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

Ruby if and ternary expressions can produce values. Their conditions use Ruby truthiness, and a selected branch may itself return false or nil without switching to the other branch. The ternary here chooses a string, then another comparison chooses a numeric flag.

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.

The target uses an if expression for the mode and a ternary for the flag, both with Bool conditions. A source integer or empty string used as a condition needs an explicit target predicate. Keep the condition's meaning distinct from the type of the branch result.

Complete Ruby comparison program:

dark = true
mode = dark ? "night" : "day"
puts mode
puts(mode == "night" ? 1 : 0)

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

Practice on your own: Swift playground