ALEPH HUB
/EN
提交
← 返回
S
Communityprompt

SwiftUI Prompt

瞄准 SwiftUI 大部分糟糕产出背后的少数几个错误:状态归属搞错、body 过大、魔法数字、以及动画绑错了值。

概览安全

状态归属放在第一位——每一块状态都要说清谁拥有、谁读、谁写,用对属性包装器,并指明对象实际在哪里创建。随后是视图结构(body 里不放业务逻辑与副作用,用 .task 而非 .onAppear 里的游离 Task)、用具名常量替代魔法数字、带稳定 ForEach 标识的布局正确性、关注失效范围的性能、绑定到具体值且尊重 Reduce Motion 的动画,以及写在代码里而非事后补的无障碍支持。最后给出一份可机械核对的常见错误清单,和一个「先画状态图」的评审提示词。

# SwiftUI

**Use when:** writing or reviewing SwiftUI views.
**Pairs with:** [ios_design.md](ios_design.md), [ios_engineering.md](ios_engineering.md)

SwiftUI has a small set of mistakes that account for most bad output: wrong state ownership, views that are too big, magic numbers, and animations that fire on the wrong thing. This prompt targets those.

---

## The prompt

```text
Write SwiftUI the way it is written in a well maintained production app.

STATE OWNERSHIP: get this right first
Before writing a view, say for each piece of state: who owns it, who
reads it, and who writes it.
- @State: owned by this view, private, value type. Always private.
- @Binding: owned elsewhere, this view writes it.
- @Observable or @StateObject: this view creates and owns the object.
- @ObservedObject or a passed observable: created elsewhere, passed in.
- @Environment: shared across a subtree, and it genuinely is shared.
Never create an object in a view's body or in an init that runs on every
update. Say where each object is created and when.
If a piece of state is read by two siblings, it belongs to the parent.
Say so rather than duplicating it.

VIEW STRUCTURE
- A body over roughly 40 lines needs breaking up. Extract a subview or a
  computed property with a real name.
- Extract by meaning, not by length. A subview should be nameable in one
  noun.
- No business logic in a view body. Views describe, they do not decide.
- No side effects in body. Body can be called many times and in any order.
- Use .task for async work tied to the view lifetime, not .onAppear with
  a detached Task. .task cancels for you.

VALUES: no magic numbers
- Every spacing, size, radius, duration, and opacity is a named constant
  grouped in one place, or comes from the design system.
- Spacing on the 4pt grid.
- Text Styles, not fixed font sizes, unless there is a stated reason.
- Semantic colours, or named colours with a light and a dark value.

LAYOUT CORRECTNESS
- Say what happens when the content is longer than expected and when it
  is empty.
- Fixed heights are suspicious. Justify each one.
- Use layout priority and frame alignment deliberately, not by trial and
  error.
- Respect safe areas. Say what happens behind the keyboard.
- Lists and grids over dynamic data use Lazy containers and stable ids.
  An id that is the array index is a bug when the array reorders.

PERFORMANCE
- Anything expensive in body will run repeatedly. Move it out.
- Give ForEach stable identity. Explain what makes each item unique.
- Watch what invalidates. A single @State on a large view redraws
  everything under it. Push state down to the smallest view that needs it.
- Avoid AnyView unless there is no alternative. Say why when you use it.

ANIMATION
- Animate a specific value with .animation(_, value:), not implicitly.
- State the duration and the curve. Say what the motion tells the user.
- Respect Reduce Motion. Provide the reduced version.
- Use matchedGeometryEffect for continuity between states, not decoration.

ACCESSIBILITY IN THE CODE, NOT LATER
- accessibilityLabel on every control whose meaning is not the visible
  text.
- accessibilityHint where the result of the action is not obvious.
- Combine related elements with accessibilityElement(children: .combine)
  where they read as one thing.
- Hide decorative images from VoiceOver.
- Verify at the largest Dynamic Type size.

PREVIEWS
Provide previews that are actually useful:
- Default state
- Empty state
- Error state
- Long content
- Dark mode
- Largest Dynamic Type size
A single preview of the happy path in light mode is not enough.

REVIEW YOUR OWN VIEW
Answer these before handing it over:
1. Which state could be owned by a smaller view than it is?
2. Which value in here is a magic number?
3. What happens when this data is empty? When it is 500 items? When a
   string is 200 characters?
4. What redraws when one thing changes? Is that more than it needs to be?
5. What does VoiceOver read out, in order?
Fix what you find.
```

---

## The three line version

```text
SwiftUI, production quality. State ownership stated explicitly for every
property. No magic numbers, every constant named. All states previewed:
empty, error, long content, dark mode, largest Dynamic Type. Then review
your own view for over sized state scope and unnecessary redraws.
```

---

## Common failures to name

Giving the model the list of specific mistakes works better than asking for quality in general.

```text
Check your code for each of these, by name:
- @StateObject or an object created inside body or in a plain init
- @State that is not private
- ForEach keyed by array index over data that can reorder
- Business logic inside body
- .onAppear launching a Task that nothing cancels
- Hardcoded font sizes and hardcoded colours
- A fixed height that breaks at large Dynamic Type
- Missing accessibility labels on icon only buttons
- AnyView used to avoid thinking about the type
- An animation applied to the whole view instead of to a value
Say for each: present or not present. If present, fix it.
```

---

## For reviewing SwiftUI

```text
Review this view.
Start with: draw the state graph. What state exists, who owns it, what
reads it, and what causes a redraw. Most SwiftUI problems are visible in
that graph before you read any layout code.
Then check layout, performance, animation, and accessibility.
```

---

## Why it works

State ownership is first because it is the root of most SwiftUI bugs and almost all SwiftUI performance problems. A model that states ownership before writing tends to get the rest right.

The named failure list works better than general instruction because these are specific patterns the model can check mechanically rather than judge.
#swiftui#ios#state-management#performance
相关推荐
Coherence Coach
AWeirdDev
Community

监看对话,找出助手可能忽略的上下文,仅在确有必要时给出提醒,否则返回 null。

promptmarkdown
React + Tailwind Product Card Component Prompt
AmirMotefaker
Community

让模型扮演资深前端工程师,生成可用于生产环境、响应式的 React + Tailwind CSS 商品卡片组件(TypeScript)。

promptmarkdown
Secure JWT Authentication Middleware
AmirMotefaker
Community

一个「角色/任务/规则」结构的提示词模板,要求模型为 Node.js + Express 设计安全的 JWT 认证中间件,包含 bcrypt 密码哈希与完整错误处理。

promptmarkdown