Why I Can Return Optional<AnyView>(nil) From Function That Returns some View?

By mistake, I did something like this:

import SwiftUI

var map: [Int:AnyView] = [:]

func ggg() -> some View {
    return map[333]

let g = ggg()

print(type(of: g))



Why I can return AnyView? from ggg()? Its return type is some View. I cannot understand why this work. is Optional<AnyView> a View?

Optional conforms to View when Wrapped conforms to View.


Thanks! That explains.

Wonder what's the purpose of doing this? Where is this useful? Seems weaken type check, allowing runtime error.

I imagine it’s useful for things like view builders’ buildIf(_:) method, which in turn supports using if statements in a view builder closure.