61
31

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]無駄にAnyViewを使っていませんか?そのAnyView、消せるかもしれません。

Posted at

型情報を消せるAnyView、便利でついつい使ってしまいますがなるべくなら使いたく無いところ。

別メソッドにしたケース

bodyの中が複雑になった時に、次のように別メソッドに分けることがあります。
some Viewでは返せないのでAnyViewにして型を揃えています。
(some Viewで返そうとすると
Function declares an opaque return type, but the return statements in its body do not have matching underlying typesと言われてコンパイルできない)


var body: some View {
  rootView
}

var rootView: AnyView {
  if isAuthorized {
    return AnyView(HomeView())  
  } else {
    return AnyView(LoginView())
  }
}

このようなケースの場合、rootViewをViewBuilderにすることでAnyViewを消すことができます。

@ViewBuilder
var rootView: some View {
      if isAuthorized {
        HomeView()
      } else {
        LoginView()
      }
    }
}
61
31
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
61
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?