Menu
CoddyTech

If and Branch Values

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

Dart supports conditional expressions with condition ? a : b. Swift also has a ternary operator and, in Swift 6, can use if as an expression when each branch supplies a compatible value. Ordinary if statements remain useful when branches perform several actions. Braces delimit Swift branches and no parentheses are required around their conditions. Do not expect assignment to produce a Boolean condition. Here an equality comparison selects an orientation label; each expression branch returns a string.

Complete Dart program. Each labelled block is a separate file.

main.dart

void main() {
  final width = 8;
  final height = 8;
  final orientation = width == height ? 'square' : 'rectangle';
  print(orientation);
}

Complete Swift program. Each labelled block is a separate file.

main.swift

import Foundation
let width = 8
let height = 8
let orientation = if width == height { "square" } else { "rectangle" }
print(orientation)
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 Dart Developers

Practice on your own: Swift playground