布尔条件
Coddy 面向 C++ 开发者的 Swift 课程 课程的第 4 课,共 48 课。
C++ 条件允许将值根据上下文转换为 bool,包括标量的零值/非零值测试以及符合条件的用户定义转换。Swift 条件要求使用 Bool。对于布尔操作数,两种语言都使用 &&、|| 和 !,并会在左侧已能确定结果时短路求值。这里使用 != 表示两个开关中恰好有一个处于开启状态。默认情况下,C++ 流输出会以数字形式打印布尔值,除非启用了 boolalpha;而 Swift 会打印小写单词。因此,示例改用明确的 on/off 标签。位运算符不遵循相同的短路约定,在某些 C++ 条件中可接受的赋值表达式,也不应在 Swift 中作为布尔值使用。
C++
完整程序文件:main.cpp。
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <memory>
#include <tuple>
#include <variant>
#include <stdexcept>
#include <algorithm>
int main() {
bool left = true, right = false;
bool alert = left != right;
std::cout << (alert ? "on" : "off") << '\n';
}
Swift
完整程序文件:main.swift。
let left = true
let right = false
let alert = left != right
print(alert ? "on" : "off")挑战
简单为闭区间实现 inside(_:low:high:)。输入包含三个整数:value、low、high,每个整数都在 -1000 到 1000 之间,且 low 不大于 high。输出 true 或 false。
实现所需的 API 和 solve(_ input: String) -> String。返回不带末尾换行符的输出文本;不要在可编辑代码中打印。锁定的驱动程序会使用其他有效输入独立检查这些 API,然后以恰好一个换行符打印返回文本。所有数值运算都保持在 Int 的范围内。
你的代码写在 Functions.swift 中。main.swift 包含提供的输入/输出代码,不能编辑。
亲手试试
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)!
// 开始公开 API 检查
let apiOK = apiChecks(input)
// 结束公开 API 检查
if apiOK { print(solve(input)) } else { print("API mismatch") }
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C++ 开发者的 Swift 课程中的所有课
自己练习: Swift 在线编辑器