Boolean Conditions
Lesson 4 of 48 in Coddy's Swift for Ruby Developers course.
Only nil and false are falsey in Ruby. Zero, empty strings and empty arrays are truthy. The || operator selects an operand, so title || "untitled" preserves an empty string and prints an empty second line. Use empty? when the intended question is whether a collection contains anything.
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 Ruby source asks whether an object is truthy, while Swift asks explicitly whether the queue or title is empty. Those are different predicates despite similar-looking fallback code. Translate the intended condition instead of mapping logical operators mechanically.
Complete Ruby comparison program:
queue = []
title = ""
puts !!queue
puts(title || "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
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 Ruby 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