Swift:如何通过Case Let访问Model变量获取RadioButton的description值
根据你描述的打印结果radioButton(RadioButtonModel(...)),大概率你的options数组元素是枚举类型,关联值为RadioButtonModel实例。下面分两种常见场景给出解决方案:
场景1:options元素是枚举类型(最可能的情况)
如果你的内容类型定义是类似包含关联值的枚举,比如:
enum ContentOption { case radioButton(RadioButtonModel) // 其他可能的case,比如checkbox(CheckboxModel)等 } // 对应的RadioButtonModel结构体(需正确实现Codable解析) struct RadioButtonModel: Codable { let description: String // 其他属性如id、isSelected等 }
那遍历options时,只需通过枚举模式匹配取出关联的RadioButtonModel,直接访问description属性即可:
// 遍历viewModel.contents找到radioButtonGroup for content in viewModel.contents { if case .radioButtonGroup(let groupModel) = content { // 遍历group的options数组 for option in groupModel.options { // 匹配radioButton枚举case,取出关联的model if case .radioButton(let radioModel) = option { // 赋值给tileView.title tileView.title = radioModel.description // 验证输出 print(radioModel.description) } } } }
场景2:options直接存储RadioButtonModel实例
如果radioButtonGroupModel.options的类型就是[RadioButtonModel],那无需额外拆包,直接访问属性即可:
for content in viewModel.contents { if case .radioButtonGroup(let groupModel) = content { for radioModel in groupModel.options { tileView.title = radioModel.description } } }
额外验证:确保JSON解析正确
要保证RadioButtonModel的description属性和JSON字段正确映射。比如你的JSON片段中radioButton对象的key是description,那结构体定义要对应;如果JSON里的key是其他名称(比如desc),需要通过CodingKeys映射:
struct RadioButtonModel: Codable { let description: String enum CodingKeys: String, CodingKey { case description = "desc" // 匹配JSON中的实际key } }
内容的提问来源于stack exchange,提问作者rainerwolfram
相关产品推荐
相关产品推荐

