【问题标题】:turn for in loops local variables into mutable variables将 for in 循环中的局部变量转换为可变变量
【发布时间】:2014-09-11 17:18:16
【问题描述】:

我在操场上编写了这段代码来代表我的问题:

import Foundation

var countries = ["Poland":["Warsaw":"foo"],"England":["London":"foo"]]

for (country, city) in countries {
  if city["London"] != nil {
   city["London"] = "Piccadilly Circus" // error because by default the variables [country and city] are constants (let)
  }
} 

有没有人知道解决方法或完成这项工作的最佳方法?

【问题讨论】:

    标签: swift


    【解决方案1】:

    您可以通过将var 添加到其声明中来使city 可变:

    for (country, var city) in countries {
    

    很遗憾,更改它不会影响您的 countries 字典,因为您会获得每个子字典的副本。为了做你想做的事,你需要遍历countries 的键并从那里改变:

    for country in countries.keys {
        if countries[country]!["London"] != nil {
           countries[country]!["London"]! = "Picadilly Circus"
        }
    }
    

    【讨论】:

    • 这实际上不是 swift 的一个很酷的功能。我猜他们在某些情况下仍然需要一些工作,特别是在字典操作方面。无论如何感谢您的回答
    • 我认为这是许多很酷的功能带来的稍微​​不方便的副作用。 :)
    【解决方案2】:

    这里有一个更符合原始代码精神的修复:

        import Foundation
    
        var countries = ["Poland":["Warsaw":"foo"],"England":["London":"foo"]]
    
        for (country, cities) in countries {
            if cities["London"] != nil {
                countries[country]!["London"] = "Piccadilly Circus"
            }
        }
    

    正如@Nate Cook 指出的那样,如果这是您的意图,请直接改变countries 值类型。 countrycities* 值只是从位于 for 循环范围内的源 countries 数据源派生的临时值类型副本。 Swift 让它们让值实际上可以帮助您看到这一点!

    注意:我将值的名称从 city 更改为 cities 以澄清语义,因为它是包含一个或多个城市的字典。

    【讨论】:

      【解决方案3】:

      很简单。

      for var (country, city) in countries {
         if city["London"] != nil {
            city["London"] = "Piccadilly Circus" 
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-06
        • 1970-01-01
        相关资源
        最近更新 更多