简体   繁体   English

在Swift中循环创建字典

[英]Create a dictionary in a loop in Swift

I have a variable set of objects that I need to place in a dictionary. 我需要在字典中放置一组可变的对象。 I'm trying to add them to the dictionary in a for loop but from what I'm understanding dictionaries are immutable so they need to be declared immediately. 我试图将它们添加到for loop的字典中for loop但是据我了解,字典是不可变的,因此需要立即声明它们。 How do I create a dictionary list of items that are not predetermined? 如何创建未预定项目的字典列表?

var newItems = [:]

for item in self.items{
  newItems["\(item.key)"]["name"] = "A new item" 
}

does not use the second value 不使用第二个值

var newItems : [String:String] = [:]

for i in 1..10{
  newItems[i.description] = "A new item" 
}

for more information https://www.weheartswift.com/dictionaries/ 有关更多信息, https://www.weheartswift.com/dictionaries/

The problem with your original code is that dictionaries only have one key, so this construct newItems["\\(item.key)"]["name"] is syntactically incorrect. 原始代码的问题在于字典仅具有一个键,因此此构造newItems["\\(item.key)"]["name"]在语法上是不正确的。 If you had a fixed number of properties you could use a struct and put that in a dictionary. 如果您具有固定数量的属性,则可以使用结构并将其放入字典中。 As you posed the question, though, you need to create a dictionary where the stored elements themselves are dictionaries. 但是,在提出问题时,您需要创建一个字典,其中存储的元素本身就是字典。 So, although I didn't actually put this into Xcode, it's a template for what you need to do: 因此,尽管我实际上并未将其放入Xcode,但它是您需要执行的操作的模板:

var newItems = [:[:]]()

for item in self.items {
    var itemDict = [:]()
    for prop in whereeveryourpropertiescomefrom {
        itemDict[prop] = valueforthisproperty
    }
    newItems["\(item.key)"] = itemDict        
}

Of course, if your properties were initially stored in a dictionary unique to this item (equivalent of the inner loop), just store it directly into newItems. 当然,如果您的属性最初存储在此项唯一的字典中(相当于内部循环),则只需将其直接存储到newItems中即可。

Then, you could reference things as 然后,您可以将事物引用为

let value = newItems["\(item.key)"]?.["property key"]

Notice the dictionary retrieval returns an optional you have to deal with. 请注意,字典检索返回您必须处理的可选内容。

解决方案是初始化字典以创建另一个字典时

var newItems: [String:[String:AnyObject]]()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM