Subhajit Halder
Subhajit Halder

Reputation: 1423

How to check values within array of dictionaries without having a key in one line

I have an array like [[URL: String]] in which I save a random string as value for each URL which is a key in my dictionary. Therefore each key is different.

I am creating a random string and want to check whether this random string is already in the array or not. For this I am doing:

let randomString = self.randomString()

for obj in randomStringArray {
    for (key, value) in obj {
        if value != randomString {
            print("not found")
        }
    }    
}

My question is: Can I write it in one line using functions of array like .filter, .contains or .first etc.?

Upvotes: 1

Views: 68

Answers (2)

Julian Benkov
Julian Benkov

Reputation: 61

Yes, you can use contains:

if !obj.values.contains(randomString) {
    print("not found")      
}

Upvotes: 0

Aravind A R
Aravind A R

Reputation: 2714

You could check whether any of the keyvalue pair in the array contains the value randomstring using contains like

  randomStringArray.contains(where:{$0.contains(where:{$1==randomString})})

Upvotes: 2

Related Questions