在swift中计算字典中的字典数

时间:2015-08-09 19:31:46

标签: xcode swift dictionary

我有一个存储在字典字典中的帐户数量,我想计算现有帐户的数量,所以基本上是“.count”,但要查找创建的字典数量。

var dictionary: [String : [ String ]] = ["" : []]
let storeString = "StoreString"

func addUpdateArray(strings: [String], index: Int) {
 let locator = storeString + index.description
 dictionary[locator] = strings
}

addUpdateArray(["Account1", "Hy"], 1)
addUpdateArray(["Account2", "Hey"], 3)

现在我想看看有多少帐户创建了这种类字典,是不是一种方式?

2 个答案:

答案 0 :(得分:1)

这样的东西?

var accounts = [String:[String:String]]() // or whatever your structure is

accounts["Edmund"] = [
    "amount": "23.87",
    "curreny": "dollars"
]

accounts["Baldrick"] = [
    "amount": "23.87",
    "curreny": "dollars"
]

accounts["Percy"] = [
    "amount": "87.00",
    "curreny": "peso"
]

println(accounts.keys.array.count) // 3

答案 1 :(得分:1)

如果您有词典词典,并且想要计算内部实际值的数量,可以这样做:

var accounts = [
    "accountsGroup1" : ["account1", "account2", "account3", "account4"],
    "accountsGroup2" : ["account1", "account2"],
    "accountsGroup3" : ["account1", "account2", "account3", "account4"]
]

let accountsCount = accounts.values.map { $0.count }
let numberOfAllAccounts = reduce(accountsCount, 0) { $0 + $1 }

println(numberOfAllAccounts)