Menu
CoddyTech

Boolean Conditions

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

Python conditions accept many objects through truth testing: an empty list is false and a nonempty list is true. Its and and or operators return one of their operands, which need not be a Boolean.

Swift conditions require Bool. Use an explicit property or comparison to obtain one. Logical operators &&, || and ! combine or invert Boolean values. The first two short-circuit, so the right side runs only when needed. Numeric zero and empty strings cannot stand in for false.

The example checks whether a queue is empty and whether a supplied title needs a fallback. In Swift, choosing between strings is a separate conditional expression. For the task, comparisons such as <= produce Boolean values that you can combine.

Complete Python comparison program:

queue = []
title = ""
print(bool(queue))
print(title or "untitled")

Complete Swift comparison program, compiled from these files:

main.swift

let queue: [Int] = []
let title = ""
print(!queue.isEmpty)
print(title.isEmpty ? "untitled" : title)
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 Python Developers

Practice on your own: Swift playground