Search code examples
iosswiftplist

Call subitems of a plist


This is my property list: directory.plist

I would like to know how call the subitems into a ViewController. This is my actual ViewController:

import UIKit

class Page1: UIViewController {

    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var positionLabel: UILabel!
    @IBOutlet weak var phoneLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!

    override func viewDidLoad() {
    super.viewDidLoad()

        Shared.instance.employees.forEach({

            nameLabel.text = (("name:", $0.name) as? String)

            print("name:", $0.name)
            print("position:", $0.position)
            print("phone:", $0.phone)
            print("email:", $0.email)
            print()
        })
    }
}

And this is the Struct I am using:

import UIKit

struct Employee {
    let position: String
    let name: String
    let email: String
    let phone: String
    init(dictionary: [String: String]) {
        self.position = dictionary["Position"] ?? ""
        self.name = dictionary["Name"] ?? ""
        self.email = dictionary["Email"] ?? ""
        self.phone = dictionary["Phone"] ?? ""
    }
}

struct Shared {
    static var instance = Shared()
    var employees: [Employee] = []
}

Inside the AppDelegate I put this:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        if let url = Bundle.main.url(forResource: "directory", withExtension: "plist"), let array = NSArray(contentsOf: url) as? [[String: String]] {
            Shared.instance.employees = array.map{Employee(dictionary: $0)}
    }
    return true

I do I have to do to call the subitems on my directory.plist? I mean the items inside the key Details. Then I wanna show the Func1, Func2 and Func3.

obs.: (this func is an abbreviation of functionary)

Thanks!


After some changes, now I got the Subitems nil: debugger


Solution

  • Your code in the application delegate is fine. You just need to update your Employee struct with another property to store the Details. But this also means that your employee dictionary isn't just a dictionary of string values. So you need to update the code to handle the proper value types:

    struct Employee {
        let position: String
        let name: String
        let email: String
        let phone: String
        let details: [String:String]
    
        init(dictionary: [String: Any]) {
            self.position = (dictionary["Position"] as? String) ?? ""
            self.name = (dictionary["Name"] as? String) ?? ""
            self.email = (dictionary["Email"] as? String) ?? ""
            self.phone = (dictionary["Phone"] as? String) ?? ""
            self.details = (dictionary["Details"] as? [String:String]) ?? [:]
        }
    }