1
normanzb
222d

When I started with javascript long time ago I thought JS is weird enough, but Swift is even more.
Why does it allow me to compile the code below? In the last line `taker.take(view)`, the `view` is an optional passed into a function that expects non-optional `some View`. How is this even possible!? I tried to change the view with some the other protocols, then it complaints, why the `View` protocol is different from the others?

```
import SwiftUI
struct ViewStruct: View {
var body: some View {
Text("")
}
}

class Taker {
func take (_ view: some View) {
print(view)
}
}

class Container {
var view:ViewStruct?

func createView() {
view = ViewStruct()
}

func test() throws {
let taker = Taker()

guard let viewIsView = view else {
throw fatalError()
}

taker.take(view)
}
}
```

Comments
  • 0
    where are the swift fanboys? should i read protocol oriented programming again?
  • 1
    I'm guessing, but I would think because the code is past your guard, the compiler is smart enough to know you already checked to make sure view wasn't null. The swift compiler is pretty smart from what I remember.
  • 1
    Swift fanboy here :)

    You are right. This is very weird.

    My guess is that View is special indeed. It might do something special for nil to EmptyView conversion maybe.

    I don‘t have time to look into it now but I‘m curios to learn what is going on here.
  • 1
    @spongessuck no, smart casting and checking is what Kotlin does.

    This particular Swift code compiles even without the guard statement.
  • 1
    I did a quick search and found this:

    https://forums.swift.org/t/...

    So apparently View is indeed special and Optional (nil) conforms to View. This might be useful for the result builders with SwiftUI's @ViewBuilder.

    I'd like to see how this is realized in code but didn't find anything yet by skimming through the code of View (which is very large).
  • 1
    Ok I think I can imagine how it is realized.

    It must be something like this:

    extension Optional: View where Wrapped: View {}

    IIRC, this is called conditional conformance.

    So, an optional/nullable value of something conforms to View if that something also conforms to View. And so nil can be passed where View is expected (but not any nil).

    And the fact that nil/Optional are implemented as enums makes it possible to do such things.

    The beauty of Swift :)
  • 1
    @Lensflare haha, thx for the research and explanation, it makes sense. TIL! (not sure if it is the beauty of swift tho haha)
Add Comment