【问题标题】:Ternary operator for tableCell description strings?tableCell 描述字符串的三元运算符?
【发布时间】:2023-04-07 04:06:01
【问题描述】:

只想用三元表达式简化else语句,因为描述是代码中唯一的变化

if LaunchDarklyEnvironment.isPromoCodeAfterRegistrationForExistingUserEnabled() == true {
                    let descriptionCell = tableView.dequeueReusableCell(withIdentifier: ScoreCardStyledPrimaryTableViewCell.reuseID) as? ScoreCardStyledPrimaryTableViewCell
                    descriptionCell?.configure(withTitle: "promo_code_after_registration_description_header".localized, description: "promo_code_after_registration_description_short".localized)
                    cell = descriptionCell
                } else{
                    let descriptionCell = tableView.dequeueReusableCell(withIdentifier: ScoreCardStyledPrimaryTableViewCell.reuseID) as? ScoreCardStyledPrimaryTableViewCell
                    descriptionCell?.configure(withTitle: "promo_code_after_registration_description_header".localized, description: "promo_code_after_registration_description".localized)
                    cell = descriptionCell
                }

【问题讨论】:

    标签: swift conditional-operator


    【解决方案1】:

    看起来您唯一要更改的是 descriptionCell?.configure 部分?

    如果是这样,一种更简单的方法是先建立一些变量:

    let shortConfiguration = "promo_code_after_registration_description_short".localized
    let normalConfiguration = "promo_code_after_registration_description".localized
    

    那么,就可以在descriptionCell配置中使用三元运算了:

    let descriptionCell = tableView.dequeueReusableCell(withIdentifier: ScoreCardStyledPrimaryTableViewCell.reuseID) as? ScoreCardStyledPrimaryTableViewCell
                    descriptionCell?.configure(withTitle: "promo_code_after_registration_description_header".localized, description: LaunchDarklyEnvironment.isPromoCodeAfterRegistrationForExistingUserEnabled() ? shortConfiguration : normalConfiguration) // <-- Add it right here
                    cell = descriptionCell
    

    (你不需要添加“== true”,因为条件无论如何都会寻找它,所以只需添加函数(我假设返回一个 Bool)就足以让三元运行)

    【讨论】:

    • 非常感谢我不了解三元,但现在我有点看你的代码了,谢谢你的真实
    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 2014-04-10
    • 1970-01-01
    • 2020-09-17
    • 2014-02-19
    • 1970-01-01
    • 2014-03-29
    • 2010-11-21
    相关资源
    最近更新 更多