ios - Proper way to get swift dictionary item index -


i have dictionary in app written in swift

var cities: [string: string] = ["":"not specified", "ny":"new york", "la":"los angeles", "sf":"san francisco"] 

i use dictionary build pickerview. when user selects 1 of items - city code saving device memory.

when user opens app next time want pickerview show saved city. how should it?

you can find index of key in dictionary higher-order functions:

let desiredkey = "ny" let pos = x.enumerate().filter { (pair: (index: int, element: (string, string))) -> bool in     return pair.element.0 == desiredkey }.map { (pair: (index: int, element: (string, string))) -> int in     return pair.index } 

pos optional(int) containing position of "ny" in current iteration order of dictionary.

store value of key somewhere (say, in user defaults), retrieve it, index of key-value pair using code above, , pass selectedrowincomponent: of picker view.

note: problem using dictionary alone backing picker order not specified explicitly. adding or removing keys may change order of existing keys. in addition, existing keys may not end in places want them - example, "" - "not specified" pair may end in middle of picker.

to fix problem, keep separate array of city keys in proper order wish follow. use array decide picker row in city displayed, , actual city using dictionary.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -