@moon791017/neo-skills 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/GEMINI.md +115 -0
- package/README.md +155 -0
- package/bin/install-claude-skills.js +72 -0
- package/commands/neo/cd-app-service.toml +20 -0
- package/commands/neo/cd-iis.toml +20 -0
- package/commands/neo/ci-dotnet.toml +21 -0
- package/commands/neo/clarification.toml +48 -0
- package/commands/neo/code-review.toml +33 -0
- package/commands/neo/dotnet-gen-interface.toml +31 -0
- package/commands/neo/explain.toml +44 -0
- package/commands/neo/git-commit.toml +49 -0
- package/dist/hooks/secret-guard.js +2 -0
- package/dist/server.js +220 -0
- package/gemini-extension.json +15 -0
- package/package.json +39 -0
- package/skills/azure-pipelines/SKILL.md +45 -0
- package/skills/azure-pipelines/templates/build/build-dotnet.yml +92 -0
- package/skills/azure-pipelines/templates/deploy/deploy-app-service.yml +71 -0
- package/skills/azure-pipelines/templates/deploy/deploy-iis.yml +189 -0
- package/skills/azure-pipelines/templates/util/clean-artifact.yml +40 -0
- package/skills/azure-pipelines/templates/util/extract-artifact.yml +57 -0
- package/skills/azure-pipelines/templates/util/iis/iis-backup.yml +92 -0
- package/skills/azure-pipelines/templates/util/iis/iis-deploy-files.yml +112 -0
- package/skills/azure-pipelines/templates/util/iis/iis-manage-website.yml +112 -0
- package/skills/azure-pipelines/templates/util/iis/iis-rollback.yml +98 -0
- package/skills/azure-pipelines/templates/util/iis/iis-start-website.yml +89 -0
- package/skills/azure-pipelines/templates/util/iis/iis-stop-website.yml +80 -0
- package/skills/azure-pipelines/templates/util/iis/iis-task.yml +157 -0
- package/skills/azure-pipelines/templates/util/set-aspnetcore-env.yml +77 -0
- package/skills/clarification/SKILL.md +22 -0
- package/skills/code-review/SKILL.md +72 -0
- package/skills/csharp/SKILL.md +87 -0
- package/skills/csharp/reference/anti-patterns.md +142 -0
- package/skills/csharp/reference/coding-style.md +86 -0
- package/skills/csharp/reference/patterns.md +142 -0
- package/skills/csharp-interface-generator/SKILL.md +40 -0
- package/skills/dotnet/SKILL.md +41 -0
- package/skills/dotnet-ef-core/SKILL.md +78 -0
- package/skills/dotnet-ef-core/reference/anti-patterns.md +51 -0
- package/skills/dotnet-ef-core/reference/coding-style.md +42 -0
- package/skills/dotnet-ef-core/reference/patterns.md +53 -0
- package/skills/dotnet-minimal-apis/SKILL.md +78 -0
- package/skills/dotnet-minimal-apis/reference/anti-patterns.md +59 -0
- package/skills/dotnet-minimal-apis/reference/coding-style.md +54 -0
- package/skills/dotnet-minimal-apis/reference/patterns.md +68 -0
- package/skills/dotnet-mvc/SKILL.md +78 -0
- package/skills/dotnet-mvc/reference/anti-patterns.md +49 -0
- package/skills/dotnet-mvc/reference/coding-style.md +43 -0
- package/skills/dotnet-mvc/reference/patterns.md +56 -0
- package/skills/dotnet-webapi/SKILL.md +78 -0
- package/skills/dotnet-webapi/reference/anti-patterns.md +48 -0
- package/skills/dotnet-webapi/reference/coding-style.md +47 -0
- package/skills/dotnet-webapi/reference/patterns.md +52 -0
- package/skills/explain/SKILL.md +27 -0
- package/skills/git-commit/SKILL.md +84 -0
- package/skills/python/SKILL.md +61 -0
- package/skills/python/reference/anti-patterns.md +177 -0
- package/skills/python/reference/coding-style.md +92 -0
- package/skills/python/reference/patterns.md +112 -0
- package/skills/python-manager/SKILL.md +61 -0
- package/skills/start-plan/SKILL.md +29 -0
- package/skills/swift/SKILL.md +78 -0
- package/skills/swift/reference/anti-patterns.md +75 -0
- package/skills/swift/reference/coding-style.md +56 -0
- package/skills/swift/reference/patterns.md +94 -0
- package/skills/swift-ui/SKILL.md +76 -0
- package/skills/swift-ui/reference/anti-patterns.md +52 -0
- package/skills/swift-ui/reference/coding-style.md +46 -0
- package/skills/swift-ui/reference/patterns.md +87 -0
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# Modern Python Style Guide: Evolution & Conventions
|
|
2
|
+
|
|
3
|
+
This guide integrates syntax evolutions from Python 3.10 to 3.14 with PEP 8 naming conventions, aimed at providing a consistent, modern, and high-quality development standard.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Part 1: Modern Syntax & Type Evolution (3.10 - 3.14)
|
|
8
|
+
|
|
9
|
+
### 1. Union Type Operator (3.10+)
|
|
10
|
+
Use `|` instead of `typing.Union` and `Optional`.
|
|
11
|
+
* **✅ Recommended:** `def process(data: int | str | None):`
|
|
12
|
+
* **❌ Avoid:** `def process(data: Union[int, str, None]):`
|
|
13
|
+
|
|
14
|
+
### 2. Structural Pattern Matching (3.10+)
|
|
15
|
+
Use `match/case` for clear data deconstruction.
|
|
16
|
+
* **✅ Recommended:**
|
|
17
|
+
```python
|
|
18
|
+
match response:
|
|
19
|
+
case {"status": 200, "data": content}:
|
|
20
|
+
return content
|
|
21
|
+
case _:
|
|
22
|
+
raise ValueError("Unknown response")
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
### 3. Self Type Annotation (3.11+)
|
|
26
|
+
Use `typing.Self` when a class method returns an instance of itself.
|
|
27
|
+
* **✅ Recommended:** `def clone(self) -> Self: return self`
|
|
28
|
+
|
|
29
|
+
### 4. Exception Groups and Propagation (3.11+)
|
|
30
|
+
Use `except*` to handle `ExceptionGroup` thrown in concurrent tasks.
|
|
31
|
+
* **✅ Recommended:**
|
|
32
|
+
```python
|
|
33
|
+
try:
|
|
34
|
+
await asyncio.gather(t1, t2)
|
|
35
|
+
except* ValueError:
|
|
36
|
+
log.error("Handling value errors")
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### 5. Simplified Generics Syntax (3.12+)
|
|
40
|
+
Use `[T]` directly after the function or class name.
|
|
41
|
+
* **✅ Recommended:** `def get_first[T](items: list[T]) -> T:`
|
|
42
|
+
* **❌ Avoid:** `T = TypeVar('T'); def get_first(items: List[T]) -> T:`
|
|
43
|
+
|
|
44
|
+
### 6. f-string Restrictions Lifted (3.12+)
|
|
45
|
+
Allows quote reuse and internal expression comments.
|
|
46
|
+
* **✅ Recommended:** `f"Name: {user["name"]}"`
|
|
47
|
+
|
|
48
|
+
### 7. Deprecation Markers and Generic Defaults (3.13+)
|
|
49
|
+
Use the `@deprecated` decorator and `Box[T = int]`.
|
|
50
|
+
|
|
51
|
+
### 8. 3.14 Preview Features
|
|
52
|
+
* **Unparenthesized Exception Catching:** `except ValueError, TypeError:`
|
|
53
|
+
* **Deferred Annotation Evaluation:** `def set_next(self, node: Node):` (no string quotes required for Node)
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Part 2: Naming Conventions (PEP 8)
|
|
58
|
+
|
|
59
|
+
### 1. Modules and Packages
|
|
60
|
+
* **Convention:** All lowercase, separated by underscores.
|
|
61
|
+
* **Example:** `data_processor.py`, `auth_utils/`
|
|
62
|
+
|
|
63
|
+
### 2. Variables, Objects, and Parameters
|
|
64
|
+
* **Convention:** **snake_case**.
|
|
65
|
+
* **Conflict Handling:** If a name conflicts with a keyword, append a trailing underscore, e.g., `id_`, `class_`.
|
|
66
|
+
* **Example:** `user_count = 5`, `def fetch(id_: int):`
|
|
67
|
+
|
|
68
|
+
### 3. Functions and Methods
|
|
69
|
+
* **Convention:** **snake_case**.
|
|
70
|
+
* **Internal Use:** Single leading underscore `_internal_method()`.
|
|
71
|
+
* **Name Mangling:** Double leading underscores `__private_attr` (to avoid collision in subclasses).
|
|
72
|
+
|
|
73
|
+
### 4. Classes and Exceptions
|
|
74
|
+
* **Convention:** **PascalCase**.
|
|
75
|
+
* **Example:** `class UserProfile:`, `class DatabaseError(Exception):`
|
|
76
|
+
|
|
77
|
+
### 5. Constants
|
|
78
|
+
* **Convention:** **SCREAMING_SNAKE_CASE**.
|
|
79
|
+
* **Example:** `MAX_RETRIES = 3`, `API_URL = "https://..."`
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## Part 3: Resource Management & Security
|
|
84
|
+
|
|
85
|
+
### 1. Context Managers
|
|
86
|
+
Always use the `with` statement to ensure resource release.
|
|
87
|
+
* **✅ Recommended:** `with open("file.txt") as f:`
|
|
88
|
+
* **❌ Avoid:** `f = open(...); f.close()`
|
|
89
|
+
|
|
90
|
+
### 2. Security (3.11+)
|
|
91
|
+
Use `LiteralString` to prevent SQL/Shell injection.
|
|
92
|
+
* **✅ Recommended:** `def query(sql: LiteralString):`
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# Modern Python Patterns (3.10 - 3.14)
|
|
2
|
+
|
|
3
|
+
This document lists recommended patterns and best practices for development in Python versions 3.10 through the latest 3.14.
|
|
4
|
+
|
|
5
|
+
## 1. Structural Pattern Matching (3.10+)
|
|
6
|
+
Use `match` statements to handle complex branching logic, data deconstruction, and Guard conditions.
|
|
7
|
+
|
|
8
|
+
### Recommended
|
|
9
|
+
```python
|
|
10
|
+
def handle_event(event: dict):
|
|
11
|
+
match event:
|
|
12
|
+
case {"type": "click", "position": (x, y)}:
|
|
13
|
+
print(f"Click at {x}, {y}")
|
|
14
|
+
case {"type": "keypress", "key": key} if key.isalnum(): # Supports Guard conditions
|
|
15
|
+
print(f"Key pressed: {key}")
|
|
16
|
+
case _:
|
|
17
|
+
print("Unknown event")
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## 2. Union Type Operator (3.10+)
|
|
21
|
+
Use `X | Y` instead of `Union[X, Y]` for more readable type annotations.
|
|
22
|
+
|
|
23
|
+
### Recommended
|
|
24
|
+
```python
|
|
25
|
+
def process_data(data: int | str | None) -> None:
|
|
26
|
+
# Supports both type hints and isinstance()
|
|
27
|
+
if isinstance(data, int | str):
|
|
28
|
+
print(f"Processing: {data}")
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## 3. Exception Handling and Concurrent Tasks (3.11+)
|
|
32
|
+
Use Exception Groups and `asyncio.TaskGroup` to manage concurrency.
|
|
33
|
+
|
|
34
|
+
### Recommended
|
|
35
|
+
```python
|
|
36
|
+
import asyncio
|
|
37
|
+
|
|
38
|
+
async def main():
|
|
39
|
+
# New code should prefer TaskGroup over asyncio.gather()
|
|
40
|
+
async with asyncio.TaskGroup() as tg:
|
|
41
|
+
tg.create_task(fetch_data())
|
|
42
|
+
tg.create_task(process_data())
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
await main()
|
|
46
|
+
except* ValueError as eg: # Use except* to handle Exception Groups
|
|
47
|
+
for e in eg.exceptions:
|
|
48
|
+
print(f"Caught error: {e}")
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## 4. Modern Generics and Type Aliases (3.12+)
|
|
52
|
+
Use the new square bracket syntax for generic declarations and the `type` keyword for type aliases.
|
|
53
|
+
|
|
54
|
+
### Recommended
|
|
55
|
+
```python
|
|
56
|
+
# Generic function declaration (PEP 695)
|
|
57
|
+
def get_first[T](items: list[T]) -> T:
|
|
58
|
+
return items[0]
|
|
59
|
+
|
|
60
|
+
# Generic classes and type aliases
|
|
61
|
+
type Point[T] = tuple[T, T]
|
|
62
|
+
|
|
63
|
+
class Container[T]:
|
|
64
|
+
def __init__(self, value: T):
|
|
65
|
+
self.value = value
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## 5. Enhanced f-strings (3.12+)
|
|
69
|
+
Leverage unrestricted f-strings to improve code flexibility.
|
|
70
|
+
|
|
71
|
+
### Recommended
|
|
72
|
+
```python
|
|
73
|
+
songs = ["Playlist A", "Playlist B"]
|
|
74
|
+
# Supports quote reuse and multiline comments
|
|
75
|
+
message = f"Songs: {
|
|
76
|
+
", ".join(songs) # Quotes can be reused internally
|
|
77
|
+
} total: {len(songs)} # Supports internal comments"
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## 6. PEP 758: Unparenthesized Exception Handling (3.14+)
|
|
81
|
+
Parentheses can be omitted when catching multiple exceptions if the exception instance is not accessed.
|
|
82
|
+
|
|
83
|
+
### Recommended
|
|
84
|
+
```python
|
|
85
|
+
try:
|
|
86
|
+
resource = fetch()
|
|
87
|
+
except ConnectionError, TimeoutError: # Omit parentheses allowed from 3.14+
|
|
88
|
+
log_error("Network request failed")
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## 7. Deferred Annotation Evaluation (3.14+)
|
|
92
|
+
String quotes are no longer required when a class refers to itself or classes not yet defined.
|
|
93
|
+
|
|
94
|
+
### Recommended
|
|
95
|
+
```python
|
|
96
|
+
class Node:
|
|
97
|
+
# 3.14 supports deferred evaluation; Node name can be used directly
|
|
98
|
+
def set_next(self, node: Node):
|
|
99
|
+
self.next = node
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## 8. Pathlib Native Operations (3.14+)
|
|
103
|
+
Prefer native copy and move methods built into `pathlib`.
|
|
104
|
+
|
|
105
|
+
### Recommended
|
|
106
|
+
```python
|
|
107
|
+
from pathlib import Path
|
|
108
|
+
|
|
109
|
+
source = Path("data.json")
|
|
110
|
+
# 3.14+ supports native copy
|
|
111
|
+
source.copy("backup.json")
|
|
112
|
+
```
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: python-manager
|
|
3
|
+
version: "1.1.0"
|
|
4
|
+
category: "Environment"
|
|
5
|
+
description: "智慧偵測與管理 Python 專案的虛擬環境與依賴套件工具(支援 uv, Poetry, venv/pip),包含工具安裝導引。"
|
|
6
|
+
compatibility: "Supports any Python project containing pyproject.toml, requirements.txt, uv.lock, or poetry.lock."
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# Python Environment Manager Skill
|
|
10
|
+
|
|
11
|
+
## Trigger On
|
|
12
|
+
- The user asks "How do I install a package?" or "Which package manager is this project using?".
|
|
13
|
+
- The user requests to add, remove, or update Python dependencies.
|
|
14
|
+
- Need to initialize a virtual environment or execute a Python script but unsure whether to use `uv run`, `poetry run`, or `python`.
|
|
15
|
+
- The project lacks explicit environment configuration and needs recommendations for suitable tools.
|
|
16
|
+
|
|
17
|
+
## Workflow
|
|
18
|
+
1. **Perceive:**
|
|
19
|
+
- Scan the project root for characteristic files: `uv.lock`, `poetry.lock`, `pyproject.toml`, `requirements.txt`.
|
|
20
|
+
- Check the system environment to test if tools are installed: execute `uv --version` or `poetry --version`.
|
|
21
|
+
2. **Reason:**
|
|
22
|
+
- Determine the tool the project should use based on characteristic files (Priority: `uv` > `Poetry` > `pip`).
|
|
23
|
+
- **Check tool availability**: If the project is determined to use `uv` but it's not installed, or if the user wants to switch to `uv/Poetry` but the environment is not ready, mark it as "Pending Installation".
|
|
24
|
+
3. **Act:**
|
|
25
|
+
- **Tool Installation Suggestion**: If the tool is not installed, **must ask the user first**: "Detected that the project uses [Tool Name], but it is not installed in your environment. Would you like me to provide the installation command and assist with the installation?"
|
|
26
|
+
- **Output Commands**: Provide the correct operation commands for the identified management tool.
|
|
27
|
+
- **Execute Changes**: If the user agrees to installation or dependency changes, provide CLI commands for user confirmation.
|
|
28
|
+
|
|
29
|
+
## Tooling Commands Reference
|
|
30
|
+
|
|
31
|
+
### 1. uv (Recommended: Ultra-fast Tool)
|
|
32
|
+
- **Detection Criteria:** `uv.lock` exists.
|
|
33
|
+
- **Installation (Unix/macOS):** `curl -LsSf https://astral.sh/uv/install.sh | sh`
|
|
34
|
+
- **Installation (Windows):** `powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"`
|
|
35
|
+
- **Common Commands:**
|
|
36
|
+
- `uv add <package>` (Add package)
|
|
37
|
+
- `uv sync` (Sync environment)
|
|
38
|
+
- `uv run <script.py>` (Run script)
|
|
39
|
+
|
|
40
|
+
### 2. Poetry
|
|
41
|
+
- **Detection Criteria:** `poetry.lock` exists or `[tool.poetry]` in `pyproject.toml`.
|
|
42
|
+
- **Installation (Cross-platform):** `curl -sSL https://install.python-poetry.org | python3 -`
|
|
43
|
+
- **Common Commands:**
|
|
44
|
+
- `poetry add <package>` (Add package)
|
|
45
|
+
- `poetry install` (Install dependencies)
|
|
46
|
+
- `poetry run python <script.py>` (Run script)
|
|
47
|
+
|
|
48
|
+
### 3. venv + pip (Legacy Standard)
|
|
49
|
+
- **Detection Criteria:** Only `requirements.txt` or `.venv` exists.
|
|
50
|
+
- **Common Commands:**
|
|
51
|
+
- `pip install <package>`
|
|
52
|
+
- `pip install -r requirements.txt`
|
|
53
|
+
|
|
54
|
+
## Deliver
|
|
55
|
+
- **Environment Detection Report:** Inform the current environment status (e.g., uv installed, poetry.lock detected).
|
|
56
|
+
- **Installation and Operation Guidance:** If tools are missing, proactively ask for installation consent and provide the correct syntax.
|
|
57
|
+
- **Environment Consistency Check:** Ensure provided commands perfectly match the project's existing lock files.
|
|
58
|
+
|
|
59
|
+
## Validate
|
|
60
|
+
- Never execute installation commands directly without asking the user.
|
|
61
|
+
- Installation commands must distinguish between operating systems (macOS/Linux vs Windows).
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: start-plan
|
|
3
|
+
description: 分析需求與專案現況,並生成詳細的開發執行計畫。
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Development Execution Planning Specification
|
|
7
|
+
|
|
8
|
+
## Perceive
|
|
9
|
+
1. **Context Gathering**: Systematically map the codebase using search tools (`grep_search`, `glob`) to understand file structures and existing patterns.
|
|
10
|
+
2. **Constraint Check**: Identify coding styles, configuration files (e.g., `package.json`, `gemini-extension.json`), and framework dependencies.
|
|
11
|
+
3. **Mandatory Deep Dive**: Validate all assumptions by reading relevant file contents. Do not skip this step.
|
|
12
|
+
|
|
13
|
+
## Reason
|
|
14
|
+
1. **Gap Analysis**: Clearly define the delta between the current codebase state and the user's desired state.
|
|
15
|
+
2. **Architectural Fit**: Ensure the proposed solution aligns with the established architecture (e.g., separating logic into `skills/`, using `commands/` for entry points).
|
|
16
|
+
3. **Risk Assessment**: Identify potential breaking changes, ambiguous requirements, or side effects.
|
|
17
|
+
4. **Dependency Chain**: Determine the strictly logical order of operations (e.g., "Create directory before creating file").
|
|
18
|
+
|
|
19
|
+
## Act
|
|
20
|
+
1. **Structure the Plan**: Present the plan to the user in **Traditional Chinese (Taiwan)** using the following mandatory sections:
|
|
21
|
+
- **🧐 現況分析 (Context Analysis)**: Relevant files and architectural overview.
|
|
22
|
+
- **🎯 執行目標 (Objectives)**: Concise summary of the mission.
|
|
23
|
+
- **🛠️ 詳細執行計畫 (Step-by-Step Plan)**: Concrete steps presented as a **numbered list** (DO NOT use Markdown tables). Each step must include:
|
|
24
|
+
- **類型**: Action Type
|
|
25
|
+
- **路徑**: File Path
|
|
26
|
+
- **說明**: Detailed description
|
|
27
|
+
- **驗證**: Verification method
|
|
28
|
+
- **⚠️ 風險與確認事項 (Risks & Questions)**: Side effects or points requiring clarification.
|
|
29
|
+
2. **Constraint**: Do not write code or modify files during the planning phase.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: swift
|
|
3
|
+
version: "1.0.0"
|
|
4
|
+
category: "Language"
|
|
5
|
+
description: "Swift 專家技能 (5.0+)。支援從基礎語法到 Swift 6 的現代開發模式,涵蓋 SwiftUI、Structured Concurrency、記憶體安全以及高效能 App 開發指引。"
|
|
6
|
+
compatibility: "Supports Swift 5.0 through 6.0+. Adaptive to iOS, macOS, and Server-side Swift environments."
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# Modern Swift (5.0+) Expert Skill
|
|
10
|
+
|
|
11
|
+
## Trigger On
|
|
12
|
+
- The user asks to write, debug, refactor, or review Swift code.
|
|
13
|
+
- The project directory contains `*.swift`, `Package.swift`, or `*.xcodeproj`.
|
|
14
|
+
- Development involves iOS (SwiftUI/UIKit), macOS, or Server-side Swift (Vapor).
|
|
15
|
+
- Code modernization is needed (e.g., migrating to Structured Concurrency or Swift 6 language mode).
|
|
16
|
+
|
|
17
|
+
## Workflow
|
|
18
|
+
1. **Perceive (Version Awareness):**
|
|
19
|
+
- Identify the Swift version (e.g., check `Package.swift` or build settings).
|
|
20
|
+
- Determine the platform (SwiftUI vs UIKit, Server vs App).
|
|
21
|
+
- Assess dependency management (Swift Package Manager, CocoaPods).
|
|
22
|
+
2. **Reason (Planning Phase):**
|
|
23
|
+
- Evaluate the use of modern syntax (e.g., `async/await`, `Result`, `@propertyWrapper`).
|
|
24
|
+
- Decide on memory management strategies (ARC, `weak/unowned`).
|
|
25
|
+
- For UI tasks, prioritize SwiftUI for modern apps or UIKit for legacy support.
|
|
26
|
+
3. **Act (Execution Phase):**
|
|
27
|
+
- Write swifty, concise code following Apple's API Design Guidelines.
|
|
28
|
+
- Implement type-safe and protocol-oriented solutions.
|
|
29
|
+
- Leverage **Structured Concurrency** (`Task`, `async let`) for asynchronous operations.
|
|
30
|
+
4. **Validate (Standard Validation):**
|
|
31
|
+
- Check for memory leaks (retain cycles) using capture lists.
|
|
32
|
+
- Verify Swift 6 concurrency safety (data race detection).
|
|
33
|
+
- Ensure naming conventions follow the standard `lowercamelCase` for members and `PascalCase` for types.
|
|
34
|
+
|
|
35
|
+
## Feature Roadmap (Swift 5.0 - 6+)
|
|
36
|
+
|
|
37
|
+
### Swift 5.0 - 5.4 (Foundation)
|
|
38
|
+
- **Result Type**: Standardized error handling.
|
|
39
|
+
- **Property Wrappers**: Encapsulating property logic (e.g., `@Published`).
|
|
40
|
+
- **Opaque Types**: Hiding implementation details (`some View`).
|
|
41
|
+
- **Result Builders**: DSL support for SwiftUI.
|
|
42
|
+
|
|
43
|
+
### Swift 5.5 - 5.10 (Modern Concurrency)
|
|
44
|
+
- **Async/Await**: Linear asynchronous code.
|
|
45
|
+
- **Actors**: Thread-safe state isolation.
|
|
46
|
+
- **Distributed Actors**: Communicating across processes.
|
|
47
|
+
- **Non-copyable Types**: Explicit control over object ownership.
|
|
48
|
+
|
|
49
|
+
### Swift 6+ (Safety & Performance)
|
|
50
|
+
- **Full Data Isolation**: Compile-time data race prevention.
|
|
51
|
+
- **Typed Throws**: Explicitly defining error types.
|
|
52
|
+
- **Embedded Swift**: Running Swift on restricted environments.
|
|
53
|
+
|
|
54
|
+
## Coding Standards
|
|
55
|
+
- **Conciseness**: Use trailing closures and shorthand argument names where appropriate.
|
|
56
|
+
- **Safety**: Prefer `if let` or `guard let` over force unwrapping (`!`).
|
|
57
|
+
- **Purity**: Prefer `struct` (Value Types) over `class` (Reference Types) for data models.
|
|
58
|
+
- **Concurrency**: Avoid `Thread.sleep` or legacy completion handlers; use structured concurrency.
|
|
59
|
+
|
|
60
|
+
## Deliver
|
|
61
|
+
- **Version-Optimized Code**: Provide code using the best features of the target Swift version.
|
|
62
|
+
- **SwiftUI/UIKit Insights**: Recommend patterns based on the UI framework used.
|
|
63
|
+
- **Concurrency Migration**: Provide strategies for moving to Swift 6 strict concurrency checks.
|
|
64
|
+
|
|
65
|
+
## Validate
|
|
66
|
+
- Ensure code compiles without warnings in the target Swift version.
|
|
67
|
+
- Validate that closure capture lists correctly handle object lifecycles.
|
|
68
|
+
- Confirm that error handling uses the `do-catch` or `throws` patterns correctly.
|
|
69
|
+
|
|
70
|
+
## Documentation
|
|
71
|
+
### Official References
|
|
72
|
+
- [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/)
|
|
73
|
+
- [The Swift Programming Language Guide](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/)
|
|
74
|
+
|
|
75
|
+
### Internal References
|
|
76
|
+
- [Swift Coding Style and Naming Conventions](reference/coding-style.md)
|
|
77
|
+
- [Swift Anti-Patterns and Best Practices](reference/anti-patterns.md)
|
|
78
|
+
- [Modern Swift Patterns Guide](reference/patterns.md)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
# Swift Anti-Patterns & Best Practices
|
|
2
|
+
|
|
3
|
+
This document highlights common pitfalls in Swift development and the recommended ways to avoid them.
|
|
4
|
+
|
|
5
|
+
## 1. Memory Management
|
|
6
|
+
|
|
7
|
+
### 1.1 Avoid Retain Cycles (Strong Reference Cycles)
|
|
8
|
+
**Problem**: Two objects holding strong references to each other will never be deallocated, causing a memory leak.
|
|
9
|
+
|
|
10
|
+
- **Bad**:
|
|
11
|
+
```swift
|
|
12
|
+
class Client {
|
|
13
|
+
var onComplete: (() -> Void)?
|
|
14
|
+
func start() {
|
|
15
|
+
onComplete = { self.doSomething() } // Retain cycle
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
```
|
|
19
|
+
- **Good**:
|
|
20
|
+
```swift
|
|
21
|
+
onComplete = { [weak self] in
|
|
22
|
+
self?.doSomething()
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
### 1.2 Avoid `unowned` for Async Work
|
|
27
|
+
**Problem**: `unowned` assumes the object will always exist. If the object is deallocated before the async work finishes, the app will crash.
|
|
28
|
+
- **Best Practice**: Use `weak` for closures that might outlive their context.
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
## 2. Optionals
|
|
33
|
+
|
|
34
|
+
### 2.1 Avoid Force Unwrapping (`!`)
|
|
35
|
+
**Problem**: Force unwrapping a `nil` value causes an immediate runtime crash.
|
|
36
|
+
|
|
37
|
+
- **Bad**: `let url = URL(string: str)!`
|
|
38
|
+
- **Good**: `guard let url = URL(string: str) else { return }`
|
|
39
|
+
|
|
40
|
+
### 2.2 Avoid Implicitly Unwrapped Optionals
|
|
41
|
+
- **Problem**: Variables like `var name: String!` are dangerous because they hide the possibility of `nil`.
|
|
42
|
+
- **Exception**: IBOutlets in iOS development are a standard exception.
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## 3. UI Patterns (App Context)
|
|
47
|
+
|
|
48
|
+
### 3.1 Avoid Massive View Controller
|
|
49
|
+
**Problem**: Putting all networking, business logic, and UI code in a single `UIViewController`.
|
|
50
|
+
- **Best Practice**: Use **MVVM** or **Clean Architecture** to separate concerns.
|
|
51
|
+
|
|
52
|
+
### 3.2 Avoid Hardcoded Strings
|
|
53
|
+
- **Best Practice**: Use `NSLocalizedString` for text and Enums for identifiers (like Segue IDs or Cell IDs).
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## 4. Concurrency
|
|
58
|
+
|
|
59
|
+
### 4.1 Avoid `Thread.sleep` or Busy Waiting
|
|
60
|
+
- **Best Practice**: Use `Task.sleep(nanoseconds:)` in Swift Concurrency or dispatch queues.
|
|
61
|
+
|
|
62
|
+
### 4.2 Avoid Main Thread Blocking
|
|
63
|
+
- **Problem**: Performing heavy I/O or network requests on `DispatchQueue.main`.
|
|
64
|
+
- **Best Practice**: Use `Task` or `background` queues, then switch back to `main` only for UI updates.
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## 5. General Design
|
|
69
|
+
|
|
70
|
+
### 5.1 Avoid Overusing Singletons
|
|
71
|
+
**Problem**: Global state makes unit testing difficult and creates hidden dependencies.
|
|
72
|
+
- **Best Practice**: Use **Dependency Injection** to pass services to objects.
|
|
73
|
+
|
|
74
|
+
### 5.2 Avoid String-based APIs
|
|
75
|
+
- **Best Practice**: Prefer Type-safe APIs. For example, use `Codable` for JSON instead of manually parsing `[String: Any]`.
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Swift Coding Conventions
|
|
2
|
+
|
|
3
|
+
This guide follows Apple's official [API Design Guidelines](https://swift.org/documentation/api-design-guidelines/) to ensure code is readable, maintainable, and "Swifty."
|
|
4
|
+
|
|
5
|
+
## 1. Naming Conventions
|
|
6
|
+
|
|
7
|
+
### 1.1 Capitalization
|
|
8
|
+
- **Types and Protocols**: Use `PascalCase` (e.g., `UserData`, `NetworkManager`).
|
|
9
|
+
- **Variables, Properties, and Methods**: Use `lowercamelCase` (e.g., `userName`, `fetchData()`).
|
|
10
|
+
- **Enums**: Use `lowercamelCase` for cases (e.g., `case success(String)`).
|
|
11
|
+
|
|
12
|
+
### 1.2 Clarity Over Brevity
|
|
13
|
+
- **Grammatical Usage**: Method names should read like English phrases.
|
|
14
|
+
- `list.insert(x, at: i)` instead of `list.put(x, i)`.
|
|
15
|
+
- **Protocols**:
|
|
16
|
+
- Protocols that describe *what* something is should be nouns (e.g., `Collection`).
|
|
17
|
+
- Protocols that describe a *capability* should end in `-able` or `-ible` (e.g., `Equatable`, `Codable`).
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 2. Code Organization
|
|
22
|
+
|
|
23
|
+
- **Extensions**: Use `extension` to group protocol conformance or logical chunks of code.
|
|
24
|
+
- **Access Control**: Be explicit with `private`, `fileprivate`, `internal` (default), and `public`. Use `private(set)` for properties that should be read-only from the outside.
|
|
25
|
+
- **File Structure**: Prefer one primary type per file.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## 3. Idiomatic Swift
|
|
30
|
+
|
|
31
|
+
### 3.1 Type Inference
|
|
32
|
+
- Let the compiler infer types when the meaning is obvious.
|
|
33
|
+
- `let names = [String]()` is preferred over `let names: [String] = []`.
|
|
34
|
+
|
|
35
|
+
### 3.2 Closures
|
|
36
|
+
- Use **Trailing Closure Syntax** whenever a closure is the last argument.
|
|
37
|
+
- `UIView.animate(withDuration: 0.3) { ... }`
|
|
38
|
+
|
|
39
|
+
### 3.3 Structs vs. Classes
|
|
40
|
+
- **Default to Structs**: Use `struct` for data models and state.
|
|
41
|
+
- **Use Classes**: Only when you need identity, inheritance, or `deinit` logic.
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## 4. Error Handling
|
|
46
|
+
|
|
47
|
+
- **Guard**: Use `guard` to exit early from functions, reducing indentation.
|
|
48
|
+
- **Optional Binding**: Use `if let` or `guard let` instead of `!` (force unwrap).
|
|
49
|
+
- **Throws**: Use `throws` for recoverable errors and `Result` for asynchronous error passing in legacy Swift (5.5+ prefers `async throws`).
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## 5. Documentation
|
|
54
|
+
|
|
55
|
+
- **Triple Slash**: Use `///` for documentation comments. This enables Quick Help in Xcode.
|
|
56
|
+
- **Parameters**: Document parameters and return values using `- Parameters:` and `- Returns:`.
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# Modern Swift Patterns Guide
|
|
2
|
+
|
|
3
|
+
This document covers recommended architectural and language patterns for Swift 5.0 through 6.0+.
|
|
4
|
+
|
|
5
|
+
## 1. Structured Concurrency (Swift 5.5+)
|
|
6
|
+
|
|
7
|
+
### 1.1 Async/Await
|
|
8
|
+
Replace completion handlers with `async` functions for linear, readable code.
|
|
9
|
+
```swift
|
|
10
|
+
func fetchUser() async throws -> User {
|
|
11
|
+
let data = try await network.request(url)
|
|
12
|
+
return try JSONDecoder().decode(User.self, from: data)
|
|
13
|
+
}
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
### 1.2 Task Groups and `async let`
|
|
17
|
+
Run multiple tasks in parallel safely.
|
|
18
|
+
```swift
|
|
19
|
+
async let avatar = downloadImage(id: 1)
|
|
20
|
+
async let profile = fetchProfile(id: 1)
|
|
21
|
+
let result = try await User(profile: profile, image: avatar)
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
## 2. State Management
|
|
27
|
+
|
|
28
|
+
### 2.1 Property Wrappers
|
|
29
|
+
Encapsulate logic for reuse across properties.
|
|
30
|
+
```swift
|
|
31
|
+
@propertyWrapper
|
|
32
|
+
struct Trimmed {
|
|
33
|
+
private var value: String = ""
|
|
34
|
+
var wrappedValue: String {
|
|
35
|
+
get { value }
|
|
36
|
+
set { value = value.trimmingCharacters(in: .whitespacesAndNewlines) }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### 2.2 Observability (Swift 5.9+)
|
|
42
|
+
Using the `@Observable` macro instead of `ObservableObject` for more efficient UI updates in SwiftUI.
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## 3. Protocol-Oriented Programming (POP)
|
|
47
|
+
|
|
48
|
+
### 3.1 Protocol Extensions
|
|
49
|
+
Provide default implementations to protocols.
|
|
50
|
+
```swift
|
|
51
|
+
protocol Validatable {
|
|
52
|
+
var isValid: Bool { get }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
extension Validatable {
|
|
56
|
+
var isValid: Bool { return true } // Default implementation
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### 3.2 Opaque Return Types
|
|
61
|
+
Return a type that conforms to a protocol without exposing the concrete type.
|
|
62
|
+
```swift
|
|
63
|
+
func makeView() -> some View { ... }
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## 4. Swift 6 Concurrency Safety
|
|
69
|
+
|
|
70
|
+
### 4.1 Actors
|
|
71
|
+
Protect mutable state from data races.
|
|
72
|
+
```swift
|
|
73
|
+
actor Counter {
|
|
74
|
+
private var value = 0
|
|
75
|
+
func increment() { value += 1 }
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### 4.2 Sendable
|
|
80
|
+
Ensure types can be safely passed between concurrent contexts.
|
|
81
|
+
```swift
|
|
82
|
+
struct Message: Sendable {
|
|
83
|
+
let text: String
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## 5. UI Architecture: MVVM
|
|
90
|
+
|
|
91
|
+
Decouple business logic from View layers (SwiftUI or UIKit).
|
|
92
|
+
- **Model**: Data structures (`struct`).
|
|
93
|
+
- **ViewModel**: Logic handler (`class` with `@Published` or `@Observable`).
|
|
94
|
+
- **View**: UI declaration.
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: swift-ui
|
|
3
|
+
version: "1.0.0"
|
|
4
|
+
category: "UI Framework"
|
|
5
|
+
description: "SwiftUI 專家技能 (iOS 16.0+)。支援從宣告式 UI 基礎到 iOS 18+ 的現代開發模式,涵蓋 NavigationStack、Observation 框架、資料流架構及高效能視圖設計。"
|
|
6
|
+
compatibility: "Requires iOS 16.0+, Swift 5.0+. Adaptive to modern iOS, iPadOS, and macOS SwiftUI development."
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
# Modern SwiftUI (iOS 16+) Expert Skill
|
|
10
|
+
|
|
11
|
+
## Trigger On
|
|
12
|
+
- The user asks to write, debug, refactor, or review SwiftUI code.
|
|
13
|
+
- The target project version is iOS 16 or higher (utilizing features like `NavigationStack`, `Grid`, etc.).
|
|
14
|
+
- Development involves state management (`@State`, `@Observable`), custom layouts, or animations.
|
|
15
|
+
|
|
16
|
+
## Workflow
|
|
17
|
+
1. **Perceive (Version and Environment Awareness):**
|
|
18
|
+
- Confirm if the deployment target is iOS 16+.
|
|
19
|
+
- Identify the current state management paradigm (traditional `ObservableObject` vs. modern `@Observable`).
|
|
20
|
+
- Assess the usage of navigation components (check if deprecated `NavigationView` is still in use).
|
|
21
|
+
2. **Reason (Planning Phase):**
|
|
22
|
+
- Plan the view hierarchy to maximize reusability and minimize redundant `body` computations.
|
|
23
|
+
- Enforce the use of `NavigationStack` or `NavigationSplitView` for navigation needs.
|
|
24
|
+
- Select the correct data flow tools based on data lifecycle (`State`, `Binding`, `Environment`).
|
|
25
|
+
3. **Act (Execution Phase):**
|
|
26
|
+
- Follow SwiftUI core principles to write concise, declarative Swift code.
|
|
27
|
+
- Use `Grid`, `ViewThatFits`, or custom `Layout` protocols to implement complex layouts.
|
|
28
|
+
- Leverage modern modifiers (e.g., `.sheet` with `detents`).
|
|
29
|
+
4. **Validate (Standard Validation):**
|
|
30
|
+
- Check for "God Views" (views with excessive logic or `body` content) and suggest splitting them.
|
|
31
|
+
- Ensure `@State` and `@Binding` are used correctly to avoid unnecessary view refreshes.
|
|
32
|
+
- Verify that the UI remains fluid and adheres to Apple's Human Interface Guidelines (HIG).
|
|
33
|
+
|
|
34
|
+
## Feature Roadmap (SwiftUI Evolution)
|
|
35
|
+
|
|
36
|
+
### iOS 13.0 - 15.0 (Foundation Era)
|
|
37
|
+
- **Declarative Syntax**: Core `View` protocol and `body` property.
|
|
38
|
+
- **State Management**: `@State`, `@Binding`, `@ObservedObject`, `@EnvironmentObject`.
|
|
39
|
+
- **Basic Containers**: `VStack`, `HStack`, `ZStack`, `List`.
|
|
40
|
+
- **Legacy Navigation**: `NavigationView` and `NavigationLink`.
|
|
41
|
+
|
|
42
|
+
### iOS 16.0 - 17.0 (Modern Era)
|
|
43
|
+
- **NavigationStack**: Decoupled and data-driven navigation pattern.
|
|
44
|
+
- **Observation Framework**: `@Observable` macro (Swift 5.9+) replacing `ObservableObject`.
|
|
45
|
+
- **Advanced Layouts**: `Grid`, `ViewThatFits`, and `Layout` protocol.
|
|
46
|
+
- **Swift Charts**: Native data visualization framework.
|
|
47
|
+
|
|
48
|
+
### iOS 18.0+ (Latest Features)
|
|
49
|
+
- **SwiftUI Animations**: New phase-based and keyframe-based animation APIs.
|
|
50
|
+
- **Interaction Enhancements**: Improved Scroll View controls and gesture handling.
|
|
51
|
+
|
|
52
|
+
## Coding Standards
|
|
53
|
+
- **Declarative Style**: Keep the view tree structure clear and avoid writing complex logic within `body`.
|
|
54
|
+
- **Modularity**: Split subviews into independent `structs` instead of computed properties.
|
|
55
|
+
- **Preview Guidelines**: Use the `#Preview` macro for rapid development, testing across multiple environment settings (Dark Mode, different locales).
|
|
56
|
+
- **Type Safety**: Prefer strongly typed navigation paths and environment keys.
|
|
57
|
+
|
|
58
|
+
## Deliver
|
|
59
|
+
- **Version-Optimized Code**: Provide code utilizing iOS 16+ features (e.g., `NavigationStack`, `presentationDetents`).
|
|
60
|
+
- **Modular View Components**: Deconstruct large views into single-responsibility, reusable components.
|
|
61
|
+
- **Modern State Management**: Prioritize the `@Observable` pattern for projects supporting Swift 5.9+.
|
|
62
|
+
|
|
63
|
+
## Validate
|
|
64
|
+
- Ensure code compiles without warnings and uses the best available APIs for the target version.
|
|
65
|
+
- Validate view `body` execution efficiency, ensuring no side effects are included.
|
|
66
|
+
- Confirm that data flow follows the unidirectional flow principle whenever possible.
|
|
67
|
+
|
|
68
|
+
## Documentation
|
|
69
|
+
### Official References
|
|
70
|
+
- [SwiftUI Documentation](https://developer.apple.com/documentation/swiftui/)
|
|
71
|
+
- [Human Interface Guidelines (Layout)](https://developer.apple.com/design/human-interface-guidelines/layout)
|
|
72
|
+
|
|
73
|
+
### Internal References
|
|
74
|
+
- [SwiftUI Coding Style and Naming Conventions](reference/coding-style.md)
|
|
75
|
+
- [SwiftUI Anti-Patterns and Best Practices](reference/anti-patterns.md)
|
|
76
|
+
- [Modern SwiftUI Patterns Guide](reference/patterns.md)
|