ページビューの合計

2026年8月27日木曜日

iOSアプリの開発(100 Days of SwiftUI) Day5 – If, switch, and the ternary operator

100 Days of SwiftUIのDay5です。

Day5の内容は以下の通りです。

1. How to check a condition is true or false

if文についてです。
どんな開発言語でもある普通の機能ですね。

文字列が空かどうかの判定
(1)""かどうか

if username == "" {
    // Make it equal to "Anonymous"
    username = "Anonymous"
}

(2)文字数が0かどうか

if username.count == 0 {
    username = "Anonymous"
}

(3)エンプティかどうか

if username.isEmpty == true {
    username = "Anonymous"
}


2. How to check multiple conditions

ifの後にはtrueかfalseになるものを書きます。
if - elseあるいはif - else if - else
で色んな条件を記述できます、この辺も他の開発言語と同じですね。

let a = false
let b = true

if a {
    print("Code to run if a is true")
} else if b {
    print("Code to run if a is false but b is true")
} else {
    print("Code to run if both a and b are false")
}


3. How to use switch statements to check multiple conditions

Switch case文ですね。
こんな感じ、でも違和感がありますね。
break文がないですね。

switch forecast {
case .sun:
    print("It should be a nice day.")
case .rain:
    print("Pack an umbrella.")
case .wind:
    print("Wear something warm")
case .snow:
    print("School is cancelled.")
case .unknown:
    print("Our forecast generator is broken!")
}

Swiftでは何も書かなくてもデフォルトでbreakの動作します。これによりbreakの書き忘れによるバグを防げます。
逆にその後の処理も継続してしたい場合は、「fallthrough」を書きます。

let day = 5
print("My true love gave to me…")

switch day {
case 5:
    print("5 golden rings")
    fallthrough
case 4:
    print("4 calling birds")
    fallthrough
case 3:
    print("3 French hens")
    fallthrough
case 2:
    print("2 turtle doves")
    fallthrough
default:
    print("A partridge in a pear tree")
}

ただし、defaultの次に実行するものがないので、defaultでfallthroughを書くとエラーになります。

4. How to use the ternary conditional operator for quick tests

三項演算子ですね。他の開発言語でもある機能です。

0 件のコメント:

コメントを投稿

iOSアプリの開発(100 Days of SwiftUI) Day 26 – Project 4, part one

100 Days of SwiftUIの Day26 です。 今日から新しいプロジェクトを始めます。SwiftUIのスキルをさらに磨きながら、プログラミングの魅力的な分野である機械学習にも挑戦していきます。 オックスフォード大学で教鞭を執るスウェーデン人教授、ニック・ボストロムは...