Boolean Conditions
Lesson 4 of 48 in Coddy's Swift for Java Developers course.
Java and Swift require a Boolean condition; a nonzero integer is not a condition. Swift spells the type Bool. The operators &&, || and ! retain their familiar short-circuit meanings.
This maintenance decision combines an explicit switch with an availability test. Parentheses can document grouping, although Swift does not require parentheses around an if condition. The right operand of && runs only when the left operand is true; the right operand of || runs only when the left operand is false.
Java: complete program
Main.java
import java.util.*;
import java.util.function.*;
public class Main {
public static void main(String[] args) throws Exception {
boolean maintenance = false;
boolean reachable = true;
System.out.println(!maintenance && reachable);
}
}Swift: complete program
main.swift
import Foundation
let maintenance = false
let reachable = true
print(!maintenance && reachable)Do not translate a Boolean operation into the bitwise integer operators. Short-circuiting is part of the expression behavior, especially when the right operand calls a function.
Challenge
EasyImplement 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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for Java Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry RulesPractice on your own: Swift playground