SwiftUI中如何访问与操作结构体数组值:随机选餐厅问题
问题修复与解释
错误原因
报错Binary operator '==' cannot be applied to operands of type '[Int]' and 'Int'的核心原因是类型不匹配:你定义的RestarauntsStruct里的id属性被设为数组类型[Int],但你生成的随机选中值是单个Int,Swift不允许直接用==比较数组和单个整数。
修复方案
根据你的JSON数据结构,分两种场景处理:
场景1:JSON中的id是单个整数(最常见情况)
如果Restaraunts.json里每个餐厅的id是单个数字(比如"id": 1),那是你定义结构体时写错了类型,修正id的类型即可:
struct RestarauntsStruct: Hashable, Codable, Identifiable { let id: Int // 将[Int]改为Int let name: String var isVisible: Bool = true // 默认全部显示 // 其他属性(如地址、评分等) }
之后按钮逻辑可以这么写(用@State管理数组状态):
@State private var restarauntsArray: [RestarauntsStruct] = [] // 按钮点击逻辑 Button("随机选餐厅") { guard !restarauntsArray.isEmpty else { return } // 生成随机选中的餐厅id let randomId = restarauntsArray.map(\.id).randomElement()! // 遍历数组更新显示状态 for index in restarauntsArray.indices { restarauntsArray[index].isVisible = (restarauntsArray[index].id == randomId) } }
场景2:JSON中的id确实是数组(特殊场景)
如果你的JSON里每个餐厅的id是数组格式(比如"id": [1,2]),那需要调整判断逻辑,检查随机数是否在id数组内:
// 按钮点击逻辑 Button("随机选餐厅") { guard !restarauntsArray.isEmpty else { return } // 先提取所有存在的id,再随机选一个 let allIds = restarauntsArray.flatMap(\.id) guard let randomId = allIds.randomElement() else { return } // 更新每个餐厅的显示状态 for index in restarauntsArray.indices { restarauntsArray[index].isVisible = restarauntsArray[index].id.contains(randomId) } }
更可靠的优化方案
如果不需要依赖id,直接用数组索引生成随机值更稳妥(避免id重复导致选中多个餐厅的问题):
Button("随机选餐厅") { guard !restarauntsArray.isEmpty else { return } let randomIndex = Int.random(in: 0..<restarauntsArray.count) for index in restarauntsArray.indices { restarauntsArray[index].isVisible = (index == randomIndex) } }
内容的提问来源于stack exchange,提问作者Stepan
相关产品推荐
相关产品推荐

