If and Branch Values
Lesson 9 of 48 in Coddy's Swift for Rust Developers course.
Rust if is an expression whose selected branch supplies a value, and a function can return its final expression without a semicolon. Swift supports explicit returns and also if expressions in suitable contexts. Both require Boolean conditions and compatible result types rather than dynamically returning arbitrary unrelated values. The source function uses a tail if expression, while the target spells out returns in each branch; both classify the same three signs. Braces delimit the Swift branch bodies even for a single statement. Preserve the order of conditions and the treatment of zero when translating a chain rather than copying surface punctuation.
Rust
fn sign(n: i32) -> &'static str {
if n < 0 { "below" } else if n == 0 { "level" } else { "above" }
}
fn main() {
println!("{}", sign(-3));
println!("{}", sign(0));
println!("{}", sign(8));
}
Swift
func sign(_ n: Int) -> String {
if n < 0 { return "below" }
else if n == 0 { return "level" }
else { return "above" }
}
print(sign(-3))
print(sign(0))
print(sign(8))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 Rust 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