0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【SwiftUI】fillの中で二項演算子使って.mintと.ultraThinMaterialを分岐させようとしたけどそれぞれColor型とMaterial型なので分岐には使えないらしい

Posted at

取り組もうとしたこと

Rectangle()
    .fill(isActive == true ? .mint : .ultraThinMaterial)

発生したエラー

Static property 'ultraThinMaterial' requires the types 'Color' and 'Material' be equivalent.

解決策

  • AnyShapeStyleというエイリアスでラップすることで解決することが出来るとのこと。
Rectangle()
    .fill(isActive == true ? AnyShapeStyle(.mint) : AnyShapeStyle(.ultraThinMaterial))

謝辞

The error produced here is a bit clearer at explaining the problem, compared to what the compiler came up with when everything was originally inlined.

So, how do you solve this? Well, SwiftUI provides a type-erased AnyShapeStyle that you can use to have dynamically different underlying shape styles based on a condition. The fix therefore is to write:

.background(!isPlayerOpen ? AnyShapeStyle(.ultraThinMaterial) : AnyShapeStyle(.clear))

By wrapping the properties like this, the return type of the condition is always AnyShapeStyle so the compiler is satisfied as the generic parameter is always resolved to the same type.

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?