如何使用三元运算符简化tableCell描述字符串的条件配置代码
代码简化方案
你代码中只有description参数的本地化key是可变项,其余逻辑完全重复,直接把可变部分替换为三元表达式即可,简化后逻辑和原代码完全一致,同时消除了重复代码:
// 公共逻辑只写一次 let descriptionCell = tableView.dequeueReusableCell(withIdentifier: ScoreCardStyledPrimaryTableViewCell.reuseID) as? ScoreCardStyledPrimaryTableViewCell // 仅可变项用三元表达式判断取值 let desc = LaunchDarklyEnvironment.isPromoCodeAfterRegistrationForExistingUserEnabled() ? "promo_code_after_registration_description_short".localized : "promo_code_after_registration_description".localized descriptionCell?.configure( withTitle: "promo_code_after_registration_description_header".localized, description: desc ) cell = descriptionCell
如果你不想额外声明变量,也可以直接把三元表达式嵌入参数位置:
let descriptionCell = tableView.dequeueReusableCell(withIdentifier: ScoreCardStyledPrimaryTableViewCell.reuseID) as? ScoreCardStyledPrimaryTableViewCell descriptionCell?.configure( withTitle: "promo_code_after_registration_description_header".localized, description: LaunchDarklyEnvironment.isPromoCodeAfterRegistrationForExistingUserEnabled() ? "promo_code_after_registration_description_short".localized : "promo_code_after_registration_description".localized ) cell = descriptionCell
优化说明
- 去掉了重复的cell初始化、配置、赋值逻辑,后续修改cell相关逻辑只需要改一处,避免维护时两边漏改
- 省略了原判断中冗余的
== true写法,Bool类型返回值可直接作为判断条件,代码更简洁
内容的提问来源于stack exchange,提问作者ZeroCooL
相关产品推荐
相关产品推荐

