Search code examples
swiftnsarraynsdictionaryplist

Swift 3 - Access item key values by array index


Hi im trying to access the items in the legs array inside my plist I want to be able to get the values for key = "title" from the legs array from this plist

I already have the method to get the values from the dictionary called abs which is the following code

let path = Bundle.main.path(forResource:"Exercise", ofType: "plist")

let dict:NSDictionary = NSDictionary(contentsOfFile: path!)!
if (dict.object(forKey: "levels") != nil) {

    if let levelDict:[String : Any] = dict.object(forKey: "levels") as? [String : Any] {

        for (key, value) in levelDict {

            if ( key == "something") {                    
                     print(value)
            }
        }
    }
}

However i have no idea how to access the legs array to get item titles


Solution

  • So I managed to find an answer to my original question

        let path = Bundle.main.path(forResource: "Exercise", ofType: "plist")
        let dict = NSDictionary(contentsOfFile: path!)!
        let levelArray:AnyObject = dict.object(forKey: "legs")! as AnyObject
    
        if let nsArray:NSArray = levelArray as? NSArray{
    
            var levelDict:AnyObject = nsArray[1] as AnyObject //currentLevel is an Int
    
            //then finally I could get data from a dictionary in the array
            let Title = levelDict["title"] as AnyObject? as! String
            print(Title)
    
        }
    

    So now this will print the second item in legs array which is "leg 2"