any と some(Existential/Opaque Type) - Swift

最終更新日: 2026-07-26

TOP(About this memo)) > 一覧(Swift) > any と some(Existential/Opaque Type)

any と some

Existential Type

let animal: Animal = Bool.random() ? dog : cat
let animal: any Animal = Bool.random() ? dog : cat

Opaque Result Type

func randomAnimal2() -> some Animal {
    Bool.random() ? Dog() : Cat()
}

具体例

struct MyView: View {
    // var body: View = Text("Hello, World!") // そもそも、anyをつけろと怒られる
    // var body: any View = Text("Hello, World!") // これだと、Viewプロトコルに準拠していないと怒られる(任意のViewだったら満たしそうにも思えるが)。
    var body: some View = Text("Hello, World!") // これだとOK。
}