Matt Falkner
Matt Falkner

Reputation: 65

changing values inside array swift at an index

I am a high school student new to swift and I can't seem to be able to change a boolean value at in index, this is my variable

var value = [[String:Bool]]()
value.append(["Club 1" : true]) 

I want to be able to change the value to false no matter how many values that I append.

I found out that you can reference them like

value[0].values.first! 

but I want to be able to change it

Thanks in advance

Upvotes: 0

Views: 883

Answers (2)

Price Ringo
Price Ringo

Reputation: 3440

I would use the following function.

func findIndexOfDictionary(inArray array: [[String: Bool]], #withKey: String) -> Int? {
    for index in 0..<array.count {
        if array[index][withKey] != nil {
            return index
        }
    }
    return nil
}

If there are no duplicate keys in any of your dictionaries, this function will return the index to the dictionary containing the key or nil if it doesn't exist.

In the Playground screen capture you can see the return value for an existing key 'Spades 2', changing the value of 'Club 1', and not finding a key 'Heart 1'.

enter image description here

Here is a more terse version of the same function using the higher order, filter function.

func findIndexOfDictionary(inArray array: [[String: Bool]], withKey key: String) -> Int? {
    return (filter(0..<array.count){array[$0][key] != nil}).first
}

Upvotes: 0

Satachito
Satachito

Reputation: 5888

value[ 0 ][ "Club 1" ] = false

Upvotes: 2

Related Questions