Swift中如何为枚举的.revisit case传递动态值?
解决方案
要给枚举的.revisit case传递动态值,你需要使用关联枚举让该case携带额外参数。由于关联枚举默认不支持CaseIterable和RawRepresentable,我们需要手动实现相关逻辑,具体代码如下:
enum MyEnum: CaseIterable { case revision case revisit(answered: Int, total: Int) // 自定义rawValue用于区分case(替代原String RawValue) var rawValue: String { switch self { case .revision: return "revision" case .revisit: return "revisit" } } // 生成动态描述文本 var description: String { switch self { case .revision: return "Do revision" case .revisit(let answered, let total): return "You answered \(answered) Out Of \(total) Questions re-start ?" } } } // 手动实现CaseIterable,提供枚举的所有基础case(revisit用占位值) extension MyEnum { static var allCases: [MyEnum] { return [.revision, .revisit(answered: 0, total: 0)] } }
使用方式
在UITableView数据源构建中,你可以根据实际数据替换.revisit的关联值:
// 构建数据源数组 var tableData: [MyEnum] = [.revision] // 动态传入实际答题数据 let answeredCount = 3 let totalCount = 3 tableData.append(.revisit(answered: answeredCount, total: totalCount)) // 在cell配置时展示描述 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let item = tableData[indexPath.row] cell.textLabel?.text = item.description return cell }
关键说明
- 关联枚举允许特定case携带自定义数据,完美解决动态值传递需求;
- 关联枚举无法自动继承
CaseIterable,通过扩展手动实现allCases,其中.revisit的占位值仅保证枚举列表完整性,实际使用时会被替换为真实数据; - 自定义
rawValue属性保留了原区分case的功能,不需要可直接移除。
内容的提问来源于stack exchange,提问作者Amit
相关产品推荐
相关产品推荐

