Boolean Conditions
Lesson 4 of 48 in Coddy's Swift for C# Developers course.
Both C# and Swift use &&, ||, and ! with Boolean operands and short-circuit the right-hand operand when the left side decides the result. Neither treats an integer as a condition. The Swift if syntax omits required parentheses but keeps braces. The example is a two-switch warning: the alert is active only when exactly one switch is on. C# prints a Boolean with an initial capital letter; Swift prints lowercase. That display difference does not change the truth table. Use explicit comparisons when adapting text output rather than relying on source-language formatting.
C#
Complete program file: Program.cs.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
bool left = true, right = false;
bool alert = left != right;
Console.WriteLine(alert ? "on" : "off");
}
}Swift
Complete program file: main.swift.
let left = true
let right = false
let alert = left != right
print(alert ? "on" : "off")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 C# 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