Menu
CoddyTech

If and Branch Values

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

Go has statement-style if and no built-in ternary conditional operator. A helper or initialized local can hold a value selected by branches. Swift additionally supports a ternary operator and suitable if expressions whose branches produce compatible values.

The source starts with audible and changes mode when quiet is true. Swift directly initializes a let binding from the if expression. Both require Boolean conditions. Use statement branching for several effects and expression branching when the purpose is selecting one value.

Go: complete program

main.go

package main
import (
    "fmt"
)

func main() {
quiet := true
    mode := "audible"
    if quiet { mode = "silent" }
    fmt.Println(mode)
}

Swift: complete program

main.swift

import Foundation
let quiet = true
let mode = if quiet { "silent" } else { "audible" }
print(mode)

A value-producing Swift if needs every outcome to provide a result. Do not assume a Go if statement itself has a value merely because its branches assign a variable.

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

Practice on your own: Swift playground