You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中更新含大量属性的Struct属性的最高效实现方式是什么?

优化方案

核心优化逻辑是不需要将Product结构体的每个属性拆分为独立的@State变量,直接用单个@State持有完整的Product实例即可,从根源上消除重复代码。

优化后代码

struct ContentView: View {
    // 单个@State持有完整Product实例,替代所有拆分的属性变量
    @State private var currentProduct: Product
    // 原始的Product数据源,支持外部传入或者本地定义
    var inputProduct = Product(id: 1, name: "Flour", price: 2.99, property1: "1", property2: "2", property3: "3", property4: "4", property5: "5")

    // 若初始数据源固定,直接在初始化时给@State赋值,可完全省略onAppear
    init() {
        _currentProduct = State(initialValue: inputProduct)
    }

    var body: some View {
        VStack {
            Text("Product ID: \(currentProduct.id)")
            Text("Product Name: \(currentProduct.name)")
            Text("Product Price: \(currentProduct.price)")
            // 后续需要使用property1-5,直接取currentProduct对应属性即可
        }
        // 若数据源会动态变化,onAppear仅需一行完成赋值,无需逐个属性处理
        .onAppear {
            currentProduct = inputProduct
        }
    }
}

方案优势

  • 大幅减少冗余代码,避免重复声明多个同类型@State变量
  • 可维护性更强,后续Product结构体新增/删除属性时,不需要同步修改视图层的状态声明
  • 状态管理逻辑统一,修改商品属性时直接操作currentProduct.xxx即可,不需要维护多份分散的状态变量

内容的提问来源于stack exchange,提问作者Nico Cobelo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:54:03