If and Branch Values
Lesson 9 of 48 in Coddy's Swift for C Developers course.
C uses the conditional operator to choose an expression value; its if statement does not itself produce a value. Swift supports a conditional operator and current Swift if expressions. Each value-producing branch must supply a compatible result rather than relying on a mutable temporary.
The examples choose a mode label from a flag. C accepts scalar conditions, while Swift requires Bool. Swift retains braces even for short branches. An if expression assigned to let makes the selected value available as a fixed binding after the choice.
C: complete program
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main(void) {
bool quiet = true;
const char *mode = quiet ? "silent" : "audible";
puts(mode);
return 0;
}
Swift: complete program
main.swift
import Foundation
let quiet = true
let mode = if quiet { "silent" } else { "audible" }
print(mode)A Swift value-producing if expression needs the alternative path. Do not assume a C statement block can be copied into an expression without considering its result.
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 C 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