0

I am writing a function that deletes a search from an apps NSUserDefaults. The method removes the deleted search from the searches Dictionary. I am confused about the syntax of this function. I don't understand how we access the value of the searches Dictionary with the searches[tags[index]]. To access the value at that index of the searches Dictionary wouldn't we just say searches[index] ?

private var searches: Dictionary <String, String> = [:] // stores tag-query pairs
private var tags: Array<String> = [] // stores tags in user-specified order

        // returns the query String for the taga at a given index
        func queryForTagAtIndex(index: Int) -> String? {
            return searches[tags[index]]
        }

1 Answer 1

1

Since your dictionary is of the type [String:String] to access or add a value to it, the key should be of type String and not Int. index is of Type Int. So it will give an error if we do return searches[index]. And since tags is of type String, we can use that as the key for the searches.

Here are some links that will help you : https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html

https://developer.apple.com/library/ios/documentation/General/Reference/SwiftStandardLibraryReference/Dictionary.html

And I would edit the code for readability purposes to this :

 private var searches:[String:String]=[String:String]() // stores tag-query pairs
 private var tags:[String] = [String]() // stores tags in user-specified order

// returns the query String for the taga at a given index
func queryForTagAtIndex(index: Int) -> String? {
   return searches[tags[index]]
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.