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

SwiftUI中调用函数填充数组报Type '()' cannot conform to 'View'如何解决

SwiftUI报错Type '()' cannot conform to 'View' 解决方案

错误原因

SwiftUI 的 body 属性被 @ViewBuilder 特性标记,内部仅允许放置符合 View 协议的元素。你在 VStack 中写入的赋值语句 ingredients = networkManager.buildIngredients(cocktail) 是无返回值的操作,返回类型为 (),不属于 View 类型,因此触发类型不匹配报错。

修复方案

无需额外声明 @State var ingredients: [String] 中间变量,直接将 networkManager.buildIngredients(cocktail) 的返回值传入 ForEach 遍历即可。如果有多处需要用到配料数组,也可以在 VStack 内部声明本地常量存储计算结果,@ViewBuilder 支持本地常量定义不会报错。
另外你原本写在 Text 上的 navigationTitle 修饰符应该移到 List 外层,符合 SwiftUI 导航设置的规范,避免重复执行。

修正后完整代码

struct DetailsView: View {
    
    @ObservedObject var networkManager = NetworkManager()
    
    let urlString: String
    
    var body: some View {
        List(networkManager.cocktails) { cocktail in
            VStack(alignment: .center) {
                HStack(alignment: .center) {
                    Text(cocktail.strDrink + "  -")
                        .frame(alignment: .center)
                    Text(cocktail.strAlcoholic)
                        .frame(alignment: .center)
                }
                
                WebImage(url: URL(string: cocktail.strDrinkThumb))
                    .resizable()
                    .frame(width: 200, height: 200, alignment: .center)
                
                Text("~ Ingredients List ~").frame(alignment: .center)
                
                // 如需多次使用配料数组可打开下方注释声明本地常量
                // let ingredients = networkManager.buildIngredients(cocktail)
                ForEach(networkManager.buildIngredients(cocktail), id: \.self) { ingredient in
                    Text(ingredient)
                }
            }
        }
        .navigationTitle("Cocktail by first letter")
        .onAppear {
            self.networkManager.fetchData(urlString)
        }
    }
}

struct DetailsView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationStack {
            DetailsView(urlString: "www.google.com")
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:36:03