Menu
CoddyTech

guardと早期脱出

Coddyの「C++開発者のためのSwift」コースのレッスン 8/48。

C++では、無効な入力や入力不在のチェックの後に早期リターンを使用するのが一般的です。Swiftのguardは残りのスコープの前提条件を表現し、そのelseブランチがそのスコープを離脱することを要求します。成功ブランチ内に制限されるif-letバインディングとは異なり、guard-letバインディングは成功後も利用可能なまま残ります。変換元のコードではstd::optional<std::string>とASCII小文字用の大文字変換ロジックを使用しているのに対し、変換先のuppercased操作はより広範なUnicodeの動作をサポートします。表示されるASCII単語の結果は一致します。guardは例外ハンドラーではなく、オプショナルをアンラップする必要もありません。任意のブール不変式を保護することができます。

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>
std::string render(std::optional<std::string> input) {
    if (!input) return "untitled";
    std::string text = *input;
    for (char &c : text) if (c >= 'a' && c <= 'z') c = static_cast<char>(c - 'a' + 'A');
    return text;
}

int main() {
std::cout << render(std::nullopt) << '\n';
    std::cout << render(std::string("go")) << '\n';
}

Swift

完全なプログラムファイル: Functions.swift。

func render(_ input: String?) -> String {
    guard let caption = input else { return "untitled" }
    return caption.uppercased()
}

完全なプログラムファイル: main.swift。

print(render(nil))
print(render("go"))
challenge icon

チャレンジ

簡単

remainder(balance:withdrawal:) を実装してください。引き出し額が0以下または残高を超える場合は拒否し、それ以外の場合は残りの残高を返します。入力は残高が0から10000、引き出し額が-100から10000の範囲です。残りの残高または rejected を出力してください。

必要なAPIおよび solve(_ input: String) -> String を実装してください。末尾に改行を含めずに出力テキストを返してください。編集可能なコード内では出力(print)を行わないでください。ロックされたドライバーは、追加の有効な入力でAPIを独立してテストし、返されたテキストを正確に1つの改行付きで出力します。すべての数値演算は Int の範囲内に収まります。

コードは Functions.swift に記述します。 main.swift には提供された入出力コードが含まれており、編集できません。

自分で試してみよう

import Foundation
func apiChecks(_ input: String) -> Bool {
return remainder(balance: 19, withdrawal: 4) == 15 && remainder(balance: 19, withdrawal: 0) == nil && remainder(balance: 19, withdrawal: 20) == nil
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// 公開APIプローブの開始
let apiOK = apiChecks(input)
// 公開APIプローブの終了
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C++開発者のためのSwiftのすべてのレッスン

自分で練習してみよう: Swiftプレイグラウンド