If and Branch Values
Lesson 9 of 48 in Coddy's Swift for PHP Developers course.
PHP's full ternary expression chooses either result, even when the selected value is false or null. Its condition follows PHP truth testing. Strict comparison with === avoids the type juggling of loose equality when a branch depends on a particular string value.
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 programs choose a night mode and then a numeric flag. Swift requires a Boolean condition, so a source expression relying on numeric or string truthiness needs an explicit target comparison. Keep conditional selection separate from unrelated state mutation.
Complete PHP comparison program:
<?php
declare(strict_types=1);
$dark = true;
$mode = $dark ? "night" : "day";
echo $mode, "\n";
echo $mode === "night" ? "1\n" : "0\n";
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
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 PHP 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