简体   繁体   中英

Get the dictionary element number in swift

I have a [string:bool] dictionary as follows

["name1":true,"name2":false,"name3":true]

I want to take the index numbers of the keys with true boolean values

    for(product,value) in products{
        if(value == true){
             print()       
     }
   }

how can I do this

This might be a more elegant, 'Swifty' solution to your problem. ForEach is a functional addition to the Swift language.

let dict = ["name1": true, "name2": false, "name3": true]
dict.forEach { (product, value) in
  if value == true { dict.index(forKey: key) }
}

Although, you can also filter on the dict , to have a new dictionary with only the records where the value is true.

let trueDict = dict.filter { return $1 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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