Menu
CoddyTech

If and Branch Values

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

A C# ternary expression chooses one of two values. Swift supports the same conditional operator and also supports suitable if expressions. Each branch of an if expression provides a single expression with a compatible type. A statement-style if is still useful when a branch performs several actions. The example selects a text label for an empty queue, not a numeric piecewise fee. In Swift, conditions use Bool and braces are mandatory. Do not move C# assignment expressions into conditions; Swift assignment does not produce the assigned value.

C#

Complete program file: Program.cs.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int waiting = 0;
        string status = waiting == 0 ? "idle" : "busy";
        Console.WriteLine(status);
    }
}

Swift

Complete program file: main.swift.

let waiting = 0
let status = if waiting == 0 { "idle" } else { "busy" }
print(status)
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 C# Developers

Practice on your own: Swift playground