惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
L
Lohrmann on Cybersecurity
aimingoo的专栏
aimingoo的专栏
V
V2EX
S
Security Affairs
T
Threatpost
C
CXSECURITY Database RSS Feed - CXSecurity.com
IT之家
IT之家
J
Java Code Geeks
The Register - Security
The Register - Security
U
Unit 42
C
CERT Recently Published Vulnerability Notes
月光博客
月光博客
A
About on SuperTechFans
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
The Blog of Author Tim Ferriss
Cisco Talos Blog
Cisco Talos Blog
Project Zero
Project Zero
S
Schneier on Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
D
DataBreaches.Net
博客园 - 司徒正美
V
Vulnerabilities – Threatpost
T
Tor Project blog
Security Latest
Security Latest
T
The Exploit Database - CXSecurity.com
T
Threat Research - Cisco Blogs
Scott Helme
Scott Helme
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
M
MIT News - Artificial intelligence
云风的 BLOG
云风的 BLOG
小众软件
小众软件
L
LangChain Blog
Attack and Defense Labs
Attack and Defense Labs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
P
Palo Alto Networks Blog
A
Arctic Wolf
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - 叶小钗
D
Darknet – Hacking Tools, Hacker News & Cyber Security
L
LINUX DO - 最新话题
MongoDB | Blog
MongoDB | Blog
Webroot Blog
Webroot Blog
H
Hacker News: Front Page
Know Your Adversary
Know Your Adversary
Spread Privacy
Spread Privacy
AWS News Blog
AWS News Blog
Engineering at Meta
Engineering at Meta

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
CLAUDE.md for Swift and iOS: 13 Rules That Stop AI From Writing Unsafe, Non-Idiomatic Apple Code
Olivia Craft · 2026-05-07 · via DEV Community

Ask Claude Code to "add a screen that loads a user profile and shows their orders" and the output compiles. It also strong-captures self in three closures, blocks the main thread on a network call, mutates @State from a background actor, and leaks a coordinator. Nothing crashes in the simulator. Everything crashes in TestFlight.

Swift is hostile to AI defaults: ARC, the SwiftUI lifecycle, Combine, structured concurrency, and a decade of UIKit history coexist in the same target. Half the model's training data is Objective-C, half is pre-async/await Swift, and the rest is SwiftUI tutorials that ignore actor isolation. A CLAUDE.md next to Package.swift is the cheapest way to pull it back to current Apple practice.

Get the full CLAUDE.md Rules Pack — oliviacraftlat.gumroad.com/l/skdgt. The 13 rules below are a free preview.

1. [weak self] in every escaping closure that touches self

ARC retain cycles are the canonical iOS leak, and AI writes them constantly: a closure captured by a long-lived publisher, Task, URLSession handler, or NotificationCenter observer that strongly references self. Every @escaping closure that mentions self opens with [weak self] in and unwraps via guard let self else { return }.

viewModel.$user
    .sink { [weak self] user in
        guard let self else { return }
        self.titleLabel.text = user.name
    }
    .store(in: &cancellables)

Enter fullscreen mode Exit fullscreen mode

Non-escaping closures (map, filter, forEach) don't need it — capture is bounded by the call.

2. Force-unwrap ! and try! are banned outside tests

user.profile!.name and try! JSONDecoder().decode(...) are the top crash signature in production iOS apps. Use guard let, if let, optional chaining, ??, or do/try/catch. Reserve ! for IBOutlet and test setup where failure is the test failing.

guard let url = URL(string: endpoint) else {
    throw APIError.invalidURL(endpoint)
}
let (data, _) = try await URLSession.shared.data(from: url)
let user = try JSONDecoder().decode(User.self, from: data)

Enter fullscreen mode Exit fullscreen mode

fatalError is allowed only for genuinely impossible states, with a message explaining why.

3. async/await only — no completion handlers in new code

If the deployment target is iOS 15+, every new async API returns async throws or uses AsyncSequence. Completion-handler closures leak callbacks, scatter error handling, and don't compose with Task cancellation. Bridge legacy APIs once via withCheckedThrowingContinuation and never again.

func loadOrders(for userID: UUID) async throws -> [Order] {
    let request = try ordersRequest(userID: userID)
    let (data, response) = try await session.data(for: request)
    try OrdersAPI.validate(response)
    return try decoder.decode([Order].self, from: data)
}

Enter fullscreen mode Exit fullscreen mode

No DispatchQueue.global().async { DispatchQueue.main.async { ... } } pyramids.

4. UI mutations run on @MainActor, full stop

Updating UIKit views or @State from a background context is a Swift 6 concurrency error and a flicker bug today. Annotate view models with @MainActor so the compiler enforces it. AI defaults to DispatchQueue.main.async — which works, but skips the actor isolation guarantee and breaks under strict concurrency.

@MainActor
final class OrdersViewModel: ObservableObject {
    @Published private(set) var orders: [Order] = []

    func refresh() async {
        do { orders = try await api.loadOrders() }
        catch { /* surface to UI */ }
    }
}

Enter fullscreen mode Exit fullscreen mode

Heavy decoding or image work goes in a non-isolated helper (or Task.detached) and the result is awaited back on the main actor.

5. Pick the right SwiftUI property wrapper, once

@State, @StateObject, @ObservedObject, @Binding, @Environment are not interchangeable, but AI uses them as if they were:

  • @State — value types owned by this view.
  • @StateObject — reference-type view models created by this view.
  • @ObservedObject — view models passed in from a parent.
  • @Binding — two-way value bindings from a parent.
  • @Environment / @EnvironmentObject — dependencies injected up the tree.
struct OrdersScreen: View {
    @StateObject private var viewModel = OrdersViewModel()  // owned here

    var body: some View {
        OrdersList(viewModel: viewModel)
    }
}

struct OrdersList: View {
    @ObservedObject var viewModel: OrdersViewModel  // passed in
    var body: some View { /* ... */ }
}

Enter fullscreen mode Exit fullscreen mode

Wrong wrapper = state thrown away on parent re-render, lifecycle bugs only visible in TestFlight.

6. Shared mutable state lives in an actor

Whenever AI writes private let queue = DispatchQueue(label: "...") to synchronize access, replace it with an actor. Locks (NSLock, os_unfair_lock) are reserved for non-async hot paths or C interop.

actor ImageCache {
    private var storage: [URL: UIImage] = [:]
    func image(for url: URL) -> UIImage? { storage[url] }
    func store(_ image: UIImage, for url: URL) { storage[url] = image }
}

Enter fullscreen mode Exit fullscreen mode

Calls become await cache.image(for: url). Data races become compile errors, not Sentry alerts.

7. Errors are typed enums conforming to LocalizedError

throw NSError(domain: "...", code: -1) is AI that gave up. Stable error conditions get an enum case; errors that cross boundaries conform to LocalizedError so they're safe to surface in UI.

enum APIError: Error, LocalizedError {
    case invalidURL(String)
    case http(status: Int)
    case decoding(underlying: Error)

    var errorDescription: String? {
        switch self {
        case .invalidURL(let s): return "Invalid URL: \(s)"
        case .http(let code):    return "Server error (\(code))"
        case .decoding:          return "Couldn't read server response"
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Callers branch on cases, not string matching.

8. Protocols + struct value types — inheritance is the last resort

AI loves class hierarchies — BaseViewController, BaseViewModel, AbstractRepository. Swift prefers protocol-oriented composition and value-type models. Use class only for real reference semantics (long-lived VMs, ARC observers, UIKit subclasses).

protocol OrdersRepository {
    func loadOrders(for userID: UUID) async throws -> [Order]
}

struct LiveOrdersRepository: OrdersRepository { /* ... */ }
struct StubOrdersRepository: OrdersRepository { /* tests */ }

Enter fullscreen mode Exit fullscreen mode

Domain models (Order, User, Money) are struct with Codable/Equatable/Sendable where applicable.

9. SwiftUI views are small, dumb, and pure

A View body that scrolls past one screen is doing too much. Extract @ViewBuilder helpers, child views, and ViewModifiers; keep state and side effects in the view model. AI defaults to god-views with inline networking — that path produces non-deterministic previews and untestable UI.

struct OrderRow: View {
    let order: Order
    var body: some View {
        HStack {
            Text(order.title).font(.body)
            Spacer()
            Text(order.total.formatted(.currency(code: "USD")))
                .monospacedDigit()
        }
        .padding(.vertical, 8)
    }
}

Enter fullscreen mode Exit fullscreen mode

No network, no @StateObject, no business logic in row views. Previews work offline.

10. UIKit interop: UIViewRepresentable for one widget, not whole flows

When something has to drop to UIKit (camera, mail composer, third-party SDK), wrap that one view in UIViewRepresentable or UIViewControllerRepresentable. AI wraps entire flows and reinvents navigation inside SwiftUI — that produces double nav stacks, broken back buttons, and coordinators that outlive their views.

struct ScannerView: UIViewControllerRepresentable {
    let onResult: (String) -> Void

    func makeUIViewController(context: Context) -> ScannerViewController {
        let vc = ScannerViewController()
        vc.onResult = onResult
        return vc
    }
    func updateUIViewController(_ vc: ScannerViewController, context: Context) {}
}

Enter fullscreen mode Exit fullscreen mode

Coordinator types exist only when you need a delegate target — and they hold self weakly.

11. Dependency injection via initializer — no singletons, no Resolver

UserDefaults.standard, URLSession.shared, and homemade ServiceLocators are the AI's go-to dependencies and they make tests impossible. Inject collaborators through the initializer; default the parameter for production. Sub them out for tests and previews.

@MainActor
final class OrdersViewModel: ObservableObject {
    private let repository: OrdersRepository
    init(repository: OrdersRepository = LiveOrdersRepository()) {
        self.repository = repository
    }
}

Enter fullscreen mode Exit fullscreen mode

@Environment carries cross-cutting concerns (theme, feature flags); everything else is constructor-injected.

12. Tests cover async paths with XCTest's async APIs — no XCTestExpectation for new code

XCTestExpectation and wait(for:timeout:) are how you tested completion handlers in 2019. New tests await directly. Use XCTUnwrap instead of !, snapshot tests for view layouts, and mock at the protocol boundary — not at URLSession.

@MainActor
final class OrdersViewModelTests: XCTestCase {
    func test_refresh_populatesOrders() async throws {
        let repo = StubOrdersRepository(orders: .sample)
        let sut = OrdersViewModel(repository: repo)

        await sut.refresh()

        XCTAssertEqual(sut.orders.count, 3)
    }
}

Enter fullscreen mode Exit fullscreen mode

CI runs xcodebuild test -enableThreadSanitizer YES on a matrix including the lowest supported iOS version.

13. Build hygiene: SwiftPM, SwiftLint, strict concurrency on

Dependencies live in Package.swift, pinned to exact or up-to-next-minor versions. SwiftLint runs in a build phase with project rules. Turn on -strict-concurrency=complete before Swift 6 forces you to. AI will add CocoaPods, disable warnings, and set SWIFT_TREAT_WARNINGS_AS_ERRORS=NO "to ship" — that's how 200-warning codebases happen.

// Package.swift
.package(url: "https://github.com/apple/swift-collections", from: "1.1.0"),

Enter fullscreen mode Exit fullscreen mode

# .swiftlint.yml
opt_in_rules:
  - force_unwrapping
  - implicit_return
  - explicit_init
disabled_rules:
  - line_length

Enter fullscreen mode Exit fullscreen mode

Warnings are errors. Force-unwrap is a lint failure. Strict concurrency catches the @MainActor violation before TestFlight does.

A starter CLAUDE.md snippet

# CLAUDE.md — iOS app

## Stack
- Swift 5.10+, iOS 16+, SwiftUI primary, UIKit only via Representable
- async/await, actors, Combine for legacy publishers, SwiftPM, XCTest

## Hard rules
- `[weak self]` + `guard let self else { return }` in every escaping closure that uses self.
- No `!`, no `try!` outside tests and IBOutlets. Use `guard let` / `do try catch`.
- New async APIs are `async throws` or `AsyncSequence`. Bridge legacy via continuation once.
- All UI mutations run on `@MainActor`. Heavy work in detached tasks, await result back.
- Pick the right wrapper: `@State` value-owned, `@StateObject` view-owned VM, `@ObservedObject` injected VM.
- Shared mutable state = `actor`. Locks only for non-async hot paths.
- Errors are typed enums conforming to `LocalizedError`. No `NSError(domain:)`.
- Protocols + `struct` first. `class` only for reference semantics.
- SwiftUI views: small, pure, no network, previews must work offline.
- UIKit via `UIViewRepresentable` for one widget, not whole flows.
- DI via initializer. No singletons, no service locators.
- Tests use async/await, `XCTUnwrap`, mock at protocol boundary, ThreadSanitizer in CI.
- SwiftPM only. SwiftLint enforced. Strict concurrency on. Warnings = errors.

Enter fullscreen mode Exit fullscreen mode

What Claude gets wrong without these rules

  • Strong-captures self in Combine sinks → view models leak forever.
  • Force-unwraps decoded JSON → first malformed payload crashes the app.
  • Updates @Published from a URLSession callback → flickers, Swift 6 errors.
  • Uses @ObservedObject instead of @StateObject → state resets on parent rerender.
  • Wraps a UIKit flow in UIViewControllerRepresentable → double back buttons.
  • Reaches for URLSession.shared everywhere → repository is impossible to test.

Drop the 13 rules above into CLAUDE.md and the next AI PR looks like an iOS app, not a SwiftUI tutorial. TestFlight stops paging you.

Want this for 20+ stacks with 200+ rules ready to paste? Grab the CLAUDE.md Rules Pack at oliviacraftlat.gumroad.com/l/skdgt.

— Olivia (@OliviaCraftLat)