0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Swift 5.9を1年遅れで検証:if and switch expressionsを触ってみた

Last updated at Posted at 2024-10-05

はじめに

現場でXcode 15が導入されました。1
なんということでしょう!!
SE-0380 if and switch expressionsが使えるではありませんか :heart_eyes:

さっそく使ってみた

以下のコードを書きました:writing_hand:

あれ?? :open_mouth:
nilの型推論ができないのでエラーになっているっぽいです。

解決策 1

userInfoの型を明記する。

func doStuff(_ message: String) -> [String: Any]? {
    let userInfo: [String: Any]? =
    if message.isEmpty {
        nil
    } else {
        [NSLocalizedDescriptionKey: message]
    }
    return userInfo
}

解決策 2

nilの型を明記する。

func doStuff(_ message: String) -> [String: Any]? {
    let userInfo =
    if message.isEmpty {
        nil as [String: Any]? 
    } else {
        [NSLocalizedDescriptionKey: message]
    }
    return userInfo
}

解決策 3

userInfoを使うのをやめて、if文returnの引数にする。

func doStuff(_ message: String) -> [String: Any]? {
    return if message.isEmpty {
        nil
    } else {
        [NSLocalizedDescriptionKey: message]
    }
}

Note: returnの後ろに改行を入れると警告が出ます。

解決策 4

returnすら要らない。

func doStuff(_ message: String) -> [String: Any]? {
    if message.isEmpty {
        nil
    } else {
        [NSLocalizedDescriptionKey: message]
    }
}

お好みの方法でお楽しみください :blush: :wave:

いいわけ

三項演算子を使って、↓こうじゃないの?というご意見もあるかと存じますが、
SE-0380を楽しんでみる趣旨から外れるので除外しております。

func doStuff(_ message: String) -> [String: Any]? {
    message.isEmpty ? nil : [NSLocalizedDescriptionKey: message]
}
  1. 執筆時、既にXcode 16がリリースされておりますが。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?