7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SwiftUI で switch を使う

Last updated at Posted at 2020-02-14
import SwiftUI

enum IconType {
    case home, search, messages
}

struct Icon: View {
    var type: IconType
    var body: some View {
        Group { () -> Image in 
            switch type {
            case .search:
                return Image(systemName: "magnifyingglass")
            case .messages:
                return Image(systemName: "envelope")
            default: // .home
                return Image(systemName: "house")
            }
        }
    }
}

Group { () -> Image inのように書けば DSL ではなく通常のクロージャとなって switch が書ける。ってか何でも書ける。自由度が一気に上がって責任も大きくなるので要注意なテクニック。

追記:

もっと手抜きするならこう。

struct Icon: View {
    var type: IconType
    var body: Image {
        switch type {
        case .search:
            return Image(systemName: "magnifyingglass")
        case .messages:
            return Image(systemName: "envelope")
        default: // .home
            return Image(systemName: "house")
        }
    }
}
7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?