Home > Software engineering >  how to get last element (array) in dictionary [string:Any]
how to get last element (array) in dictionary [string:Any]

Time:03-15

i have a dictionary plist and i have to get an array from that dictionary which is in the last. i have to get that array in my table

    var dict = [String: Any]()
     
    func readAndWriteData(){
    if let path = Bundle.main.path(forResource: "Property List", ofType: "plist") {
        var dictionary : NSDictionary?
        if var array = NSArray(contentsOfFile: path)?.firstObject as? [String:Any] {
           // array["hello"] = "hello"
            // i have get these value by using key of each values
            print(array)
            tableView.reloadData()
        }else{
            dictionary = NSDictionary(contentsOfFile: path)
            dict = dictionary as! [String:Any]
            print(dict["featureImageArray"])              
        }
    }
}

this is my plist

CodePudding user response:

First of all you are using pretty objective-c-ish API to get and parse the property list. Don't do that, use Swift native types and there is a dedicated class to (de)serialize property lists.

And there is no last item in the dictionary. You get the array by key featureImageArray

var array = [[String:Any]]()

func readAndWriteData(){
    let url = Bundle.main.url(forResource: "Property List", withExtension: "plist")!
    do {
        let data = try Data(contentsOf: url)
        let propertyList = try PropertyListSerialization.propertyList(from: data, format: nil) as! [String:Any]
        array = propertyList["featureImageArray"] as! [[String:Any]]
        tableView.reloadData()
    } catch {
        print(error)
    }
}

A still better way is to use custom structs and PropertyListDecoder.

  • Related