【问题标题】:how to change dynamic the value of dictionary with a for in loop in swift如何在swift中使用for in循环动态更改字典的值
【发布时间】:2016-11-26 15:54:59
【问题描述】:
func answersAndResults (answerIndex: Int, link: Dictionary <Int, Int>) {
    if inputIndex == answerIndex {
        for (linkedResult, weight) in link {
            linkedResult += weight // Left side of mutating operator isn't immutable: "linkedResul" is a let costant
        }

    }
}

如何使用 for in 循环动态更改字典的值

【问题讨论】:

  • 无关,但您需要学习使用正确的命名约定。只有类名应该以大写字母开头。变量、方法和参数名称都应以小写字母开头。你的函数应该是func answersAndResults (answerIndex: Int, link: Dictionary &lt;Int, Int&gt;)。遵循标准使您的代码更容易被其他人阅读。

标签: swift dictionary for-loop


【解决方案1】:

Swift 字典是值类型,因此当您将它们作为参数传递给函数时,函数将接收字典的letcopy。如果您希望该函数修改您传入的原始字典,则必须将其设为inout 参数。这会将您在函数中所做的任何更改的结果复制回原始字典 var。

要记住的第二点是,在您的 for 循环中,您还将获得每个键和值的不可变 副本(因为它们是 Ints,它们也是值类型,而不是引用类型) ,因此您需要在原始字典上设置新值,而不仅仅是尝试在循环内增加副本。

结合以上几点,你可以把你的函数改成这样:

func answersAndResults (answerIndex: Int, link: inout [Int:Int]) {
    if inputIndex == answerIndex {
        for (linkedResult, weight) in link {
            link[linkedResult] == linkedResult + weight
        }
    }
}

另请注意,[Int:Int]Dictionary&lt;Int, Int&gt; 的更传统的 Swift 简写。

【讨论】:

    猜你喜欢
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 2020-10-13
    • 2020-05-30
    • 2015-05-05
    • 2015-07-31
    相关资源
    最近更新 更多