Menu
CoddyTech

Boolean Conditions

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

R if expects a nonmissing condition of length one, with permitted coercion to logical. A length-zero vector or NA is not a usable condition, and modern R rejects longer conditions. && and || perform scalar short-circuit logic; & and | work elementwise. Test collection length or string content explicitly.

Swift conditions require Bool. Ask an array or string whether it isEmpty, compare a number, or use another explicit Boolean predicate. Combine Boolean conditions with &&, || and !. A conditional expression selects a string; logical operators do not act as general operand selectors.

The source uses length and nzchar to produce scalar decisions instead of passing whole vectors into if. Swift's explicit isEmpty test serves the same purpose for its collection values. A missing logical value requires a policy before either language can choose a normal branch.

Complete R comparison program:

queue <- integer()
title <- ""
cat(tolower(as.character(length(queue) > 0L)), "\n", sep = "")
cat(if (nzchar(title)) title else "untitled", "\n", sep = "")

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

Practice on your own: Swift playground