【问题标题】:I am trying to create a function that increases an employees salary if they are on the promotion list我正在尝试创建一个功能,如果他们在晋升名单上,可以增加员工的薪水
【发布时间】:2019-10-19 10:37:34
【问题描述】:

我试图弄清楚如何通过测试字典键与数组值的相等性来编辑字典中的值

所以我几乎想通了,我一直试图用从函数返回的值替换字典中的值。

for (key, value) in employeeSal {

    for name in promotionList {

        if key == name {

            promotion(salary: value)

            print(key, promotion(salary: value))
            employeeSal[key: value]

        }   
    }
}

print(key, Promotion(salary: value) 向我展示了我想要的效果。我尝试将新值分配给键, employeeSal[key: value],但它不起作用,我没有想法。

【问题讨论】:

    标签: swift loops dictionary


    【解决方案1】:

    promotion 的结果赋值给一个变量。这。用它来更新字典。

    let newSalary = promotion(salary: value)
    employeeSal[key] = newSalary
    

    有一个更有效的解决方案:

    for name in promotionList {
        if let value = employeeSal[name] {
            let newSalary = promotion(salary: value)
            employeeSal[name] = newSalary
        }
    }
    

    【讨论】:

    • 谢谢你。我最终能够使用:````employeeSal.updateValue(newSalary, forKey: key) 。 ````
    • 或者只使用我发布的代码。不需要updateValue
    • 好的。我会试一试。谢谢。
    猜你喜欢
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    相关资源
    最近更新 更多