Menu
CoddyTech

Boolean Conditions

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

Swift and Kotlin conditions require Boolean values; neither treats a nonzero integer as true. Both languages short-circuit logical AND and OR. The right operand of AND runs only when the left is true, and the right operand of OR runs only when the left is false. This matters when an expression calls a function or checks a collection before indexing it. The examples use a visible side effect so you can see which calls happen. Negation uses ! in both languages. Parenthesize mixed conditions when the intended grouping would otherwise be hard to read, especially when porting a compound Kotlin predicate.

Kotlin

fun ping(): Boolean { println("called"); return true }
fun main() {
    println(false && ping())
    println(true || ping())
}

Swift

func ping() -> Bool { print("called"); return true }
print(false && ping())
print(true || ping())
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 Kotlin Developers

Practice on your own: Swift playground