加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 将for局部变量转换为可变变量

发布时间:2020-12-14 02:28:28 所属栏目:百科 来源:网络整理
导读:我在操场上制作的这段代码代表了我的问题: import Foundationvar countries = ["Poland":["Warsaw":"foo"],"England":["London":"foo"]]for (country,city) in countries { if city["London"] != nil { city["London"] = "Piccadilly Circus" // error beca
我在操场上制作的这段代码代表了我的问题:
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)
  }
}

有没有人知道一项工作或最好的方法来使这项工作?

您可以通过在其声明中添加var来使city变为可变:
for (country,var city) in countries {

不幸的是,更改它不会影响您的国家/地区词典,因为您将获得每个子词典的副本.要做你想做的事,你需要遍历国家的钥匙并从那里改变一切:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读