-1

I have dictionary :

var DictPl11 = [Int: String]()

I want to check for all integers, that are connected with one same string. For example with string "0":

DictPl11 = [1: "0", 4: "1", 3: "0", 6: "0"]

I want to print Int values 1, 3, 6

Thank you

Toby V.
  • 425
  • 1
  • 6
  • 15
  • Show us some of your codes. The steps and codes you've tried in PlayGround or in your project. – Glenn Posadas Feb 17 '17 at 17:23
  • So you're looking for all the keys that have a particular value? (If so, dupe of [Swift dictionary get key for value](http://stackoverflow.com/q/27218669/2976878)) – Hamish Feb 17 '17 at 17:29
  • I suggest you give `DictPl11` a better name. Swift's convention is to name variables with lowerCamelCase. – Alexander Feb 17 '17 at 17:36

2 Answers2

1

For that you can try like this way.

var DictPl11 = [1: "0", 4: "1", 3: "0", 6: "0"]
var keyArray = DictPl11.flatMap { $1 == "0" ? $0 : nil } 
// [1, 3, 6] Keep in mind that this array doesn't have any order
Nirav D
  • 71,513
  • 12
  • 161
  • 183
0

You can try everything in PlayGround before asking, by the way.

You probably need to explicitly declare the type of your variable DictPl11 as [Int: String], as it crashed in my PlayGround.

By fast enumerating, you can get and print the key and value of your dictionary like so:

var DictPl11 = [1: "0", 4: "1", 3: "0", 6: "0"] as [Int: String]

for (key, value) in DictPl11 {
    print("key: \(key)")
    print("value: \(value)")
}
Glenn Posadas
  • 12,555
  • 6
  • 54
  • 95