Skip to content

引数を持つmodifierを提供する #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Guide.docc/Articles/ProvideModifierWithParameter.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# 引数を持つmodifierを提供する

引数内で状態の条件分岐を記述できるよう、引数を持つmodifierを提供します。

## Overview

SwiftUIでは、条件に応じてViewの見た目や振る舞いを変更することがよくあります。引数のないmodifierを使用する場合、利用側は`if`文による条件分岐を使用するしかありませんが、これはView identityが変更され、パフォーマンスの低下を招きます。

引数を持つmodifierを提供することで、利用側はmodifierの引数の中で条件分岐を記述でき、View identityを保持したままmodifierを条件によって変更できます。

### 引数のないmodifierの問題点

引数のないmodifierを条件分岐によって切り替えるには、`if`文を使用する必要があります:

```swift

struct ContentView: View {
@State var condition = false

var body: some View {
xxx
}
}
```

この実装では、`condition`の値が変わるたびに、`Text`がView identityの異なるViewに再構築されます。これにより、状態変更のたびに完全な再構築が必要となり、パフォーマンスが低下します。

### 条件分岐をmodifierの引数に移動する

引数を持つmodifierを提供すると、条件分岐を引数に移動することで同一のView identityで表現できます:

```swift
xxx
```
1 change: 1 addition & 0 deletions Guide.docc/SwiftUIViewCodingGuidelines.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@

### The Art of API Design
- <doc:ProvidesContainerViewAccessViaProxy>
- <doc:ProvideModifierWithParameter>

### Key priciples of the User Interface
- <doc:UserOwnsTheirInput>
Expand Down