2
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?

More than 1 year has passed since last update.

[SwiftUI] [any Protocol] な配列の List を表示する方法

Last updated at Posted at 2023-08-08

概要

どういうことかというと、以下のような配列を List で表示させる方法を本記事では紹介したいと思います。

protocol Animal: Identifiable where ID == UUID {
    var id: Self.ID { get }
    var name: String { get } 
}


struct Human: Animal {
    let id: UUID = .init()
    let name: String
}

struct Dog: Animal {
    let id: UUID = .init()
    let name: String
}

struct Cat: Animal {
    let id: UUID = .init()
    let name: String
}

// これ↓
let animals: [any Animal] = [
    Human(name: "タロウ"),
    Human(name: "ジロウ"),
    Dog(name: "ハチ"),
    Dog(name: "ポチ"),
    Cat(name: "ふてニャン"),
    Cat(name: "クロ")
]

やり方

  • Swift の case ... 系の書き方は if / guard でも使用可能です。

// MARK: - case let ... as SomeType
// switch 文だとこう
switch hoge {
case let fuga as SomeType:
    return
default:
    break
}

// guard 文だとこんな感じ 
guard case let fuga as SomeType = hoge else { return }


// MARK: - case let .some(...)
// switch 文だとこう
switch hoge {
case .some(let fuga):
    return
default:
    break
}

// guard 文だとこんな感じ
guard case let .some(fuga) = hoge else { return }
// もしくは 
guard case .some(let fuga) = hoge else { return }
  • 以下、実際のコードです。
import SwiftUI
import PlaygroundSupport

(中略)

let animals: [any Animal] = [
    Human(name: "タロウ"),
    Human(name: "ジロウ"),
    Dog(name: "ハチ"),
    Dog(name: "ポチ"),
    Cat(name: "ふてニャン"),
    Cat(name: "クロ")
]

struct ContentView: View {
    var body: some View {
        List(animals, id: \.id) { animal in
            if case let human as Human = animal {
                HStack {
                    Text("🧍")

                    Text(human.name)
                }
            }

            if case let dog as Dog = animal {
                HStack {
                    Text("🐶")

                    Text(dog.name)
                }
            }

            if case let cat as Cat = animal {
                HStack {
                    Text("🐱")

                    Text(cat.name)
                }
            }
        }
    }
}

PlaygroundPage.current.setLiveView(ContentView())

実際のスクショ

image.png

最後に

間違い、ご指摘事項等あればお気軽に編集リクエスト/コメントいただければ幸いです☺️

2
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
2
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?