Menu
CoddyTech

Boolean Conditions

Lesson 4 of 48 in Coddy's Swift for C++ Developers course.

C++ conditions allow contextual conversion to bool, including scalar zero/nonzero tests and eligible user-defined conversions. Swift conditions require Bool. With Boolean operands, both languages use &&, || and ! and short-circuit when the left side decides the result. This comparison uses != to express that exactly one switch is active. C++ stream output prints booleans numerically by default unless boolalpha is enabled, while Swift prints lowercase words; the examples choose explicit on/off labels instead. Bitwise operators do not have the same short-circuit contract, and assignment expressions accepted in some C++ conditions should not be carried into Swift as Boolean values.

C++

Complete program file: main.cpp.

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>

int main() {
bool left = true, right = false;
    bool alert = left != right;
    std::cout << (alert ? "on" : "off") << '\n';
}

Swift

Complete program file: main.swift.

let left = true
let right = false
let alert = left != right
print(alert ? "on" : "off")
challenge icon

Challenge

Easy

Implement inside(_:low:high:) for a closed interval. Input has three integers: value, low, high, each -1000 through 1000 with low no greater than high. Output true or false.

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 inside(7, low: 7, high: 9) && !inside(10, low: 7, high: 9) && inside(9, low: 7, high: 9)
}
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