简体   繁体   English

快速创建带有for循环的字典

[英]create a dictonary with for loop in swift

I just want to create a dictionary with the help of for loop sample code : 我只想在for循环示例代码的帮助下创建一个字典:

var counter: Int = 1;
var pageCountDict = [String:Any]();
    for filterCount in counter..<6
    {
       if let count = "page_\(filterCount)_vtime" as? String
       {
          pageCountDict = [count: timeInterval_Int];
       }
    }
print(pageCountDict);

This print command give me only last value of forloop 这个打印命令只给我forloop的最后一个值
I just want all the value of this variable pageCountDict in a dictonary 我只想要字典中该变量pageCountDict的所有值

The way to assign to a dictionary is first use the subscript and assign the value to it: 分配给字典的方法是首先使用下标并为其分配值:

pageCountDict[YourKey] = YourValue

Also, you can see many examples and explanations in Apple documentation regarding dictionaries. 另外,您可以在Apple文档中查看有关词典的许多示例和说明。

With each loop, you are replacing the dictionary with one that contains only one element. 对于每个循环,您都将字典替换为仅包含一个元素的字典。 What you want to do is this : 您要执行的操作是:

pageCountDict[count] = timeInterval_Int

Also, you shouldn't need the as? String 另外,您是否不需要as? String as? String part. as? String部分。 This should be sufficient : 这应该足够了:

for filterCount in counter..<6
{
    pageCountDict[count] = "page_\(filterCount)_vtime"
}

var pageCountDict = [String:Any]()

You can add values to this dictionary by merging previous contents and new data as follows... 您可以通过合并以前的内容和新数据,向此字典添加值,如下所示...

let counter: Int = 1
var pageCountDict = [String:Any]()
for filterCount in counter..<6
{
   let value = 9
   let count = "page_\(filterCount)_vtime" //'if' is not needed as it is always true
   pageCountDict.merge([count: timeInterval_Int], uniquingKeysWith:{ (key, value) -> Any in
        //assign value for similar key
        timeInterval_Int
    })
}
print(pageCountDict)`

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

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