Swift: Dictionary Access via Index

How do I get the key at a specific index from a Dictionary in Swift?

That's because keys returns LazyMapCollection<[Key : Value], Key>, which can't be subscripted with an Int. One way to handle this is to advance the dictionary's startIndex by the integer that you wanted to subscript by, for example:

let intIndex = 1 // where intIndex < myDictionary.count
let index = myDictionary.index(myDictionary.startIndex, offsetBy: intIndex)
myDictionary.keys[index]

Another possible solution would be to initialize an array with keys as input, then you can use integer subscripts on the result:

let firstKey = Array(myDictionary.keys)[0] // or .first

Remember, dictionaries are inherently unordered, so don't expect the key at a given index to always be the same.

Swift: dictionary access via index

you can get the keys array and get the key at indexPath.section like this:

Array(yourDictionary.keys)[indexPath.section]

and you can get the value at indexPath.row from the values array like this:

Array(yourDictionary.values)[indexPath.row]

Edit:

if you want to get the values of a specific section key you should write:

let key = Array(yourDictionary.keys)[indexPath.section]
let array = yourDictionary[key]
let value = array[indexPath.row]

Get index of item in dictionary by key in Swift

If I understand you correctly, you could do it like so:

let myList = [
2: "Hello",
4: "Goodbye",
8: "Whats up",
16: "Hey"
]

let index = Array(myList.keys).index(of: property.propertyValue)

And then to find the key you're looking for again...

let key = Array(myList.keys)[index!]

As said in other answers, a dictionary is probably not the data structure you're looking for. But this should answer the question you've asked.

Access a Dictionary index saved in Swift session

Basically never use value(forKey with UserDefaults.

There is a dedicated API dictionary(forKey which returns [String:Any]? by default. In your case conditionally downcast the dictionary to [String:String].

if let sessionData = preferences.dictionary(forKey: "session") as? [String:String] {
print(sessionData["user_id"]!)
} else {
print("sessionData is not available")
}

And this is not JavaScript. Please name variables lowerCamelCased.


A more sophisticated way is to use a struct and save it with Codable

struct Session : Codable {
let userID, name, email : String
}

let preferences = UserDefaults.standard
let sessionInfo = Session(userID:"123", name: "John", email: "john@doe.com")
let sessionData = try! JSONEncoder().encode(sessionInfo)
preferences.set(sessionData, forKey: "session")

do {
if let sessionData = preferences.data(forKey: "session") {
let sessionInfo = try JSONDecoder().decode(Session.self, from: sessionData)
print(sessionInfo.userID)
}
} catch { print(error) }

How to access dictionary key via index?

In Swift 2 the equivalent of dict.keys.array would be Array(dict.keys):

let dict = ["item1":1, "item2":2, "item3":3]

let firstKey = Array(dict.keys)[0] // "item3"

Note: of course, as dictionaries are unordered collections, "first key" of the resulting array may not have a predictable value.

How to get the key, value and index in a Dictionary loop?

Dictionaries are unordered, so all you can do is to enumerate through the dictionary, like this:

func getKeyValueIndex() {
if let myDict = myDict {
for (index, dict) in myDict.enumerated() { print(index, dict.key, dict.value) }
}
}

How to access indices of an NSDictionary, and convert that key’s value to an Int in Swift?

You can't access a dictionary's [nth] index like you would an array because a dictionary is an unordered collection. Instead you would have to do something like this [CORRECTED] hoursDictionary[0]["open"][5]["end"], or whatever sequence to get the value you need.

Or, I tend to split this up so I can ensure I am processing each step correctly like so:

guard let hoursDictionaries = responseDictionary.value(forKey: "hours") as? [NSDictionary] else {return}

if let firstHoursDictionary = hoursDictionaries[0] as? NSDictionary,
let openDictionarys = firstHoursDictionary["open"] as? [NSDictionary],
let firstOpenDictionary = openDictionarys[5] as? NSDictionary,
let endTimeAsString = firstOpenDictionary["end"] as? String,
let endTimeAsInt = Int(endTimeAsString),
endTimeAsInt > someInt {

// Do something
}

// Remember, you can always check what type the compiler is inferring something
// to be by right-clicking on the variable name and clicking `Show Quick Help`.


Related Topics



Leave a reply



Submit