Doc Doc - 1 month ago 129
iOS Question

How to read from a plist with Swift 3 iOS app

-Disclaimer-

I'm extremely new to iOS and Swift development, but I'm not particularly new to programming.


I have a basic

iOS
application with
Swift3
elements in it.
I've created a
plist
file with some entries I want to read and use in my application.


How can you read a value for a given key for a bundled
plist
file, in Swift3?



This seems like a really simple question to me, but a bunch of searching is making me question my whole conceptual approach.

Helpful tips would be appreciated.

Answer

Same way you have done in Swift 2.3 or lower just syntax is changed.

if let path = Bundle.main.path(forResource: "fileName", ofType: "plist") {

    //If your plist contain root as Array
    if let array = NSArray(contentsOfFile: path) as? [[String: Any]] {

    }

    ////If your plist contain root as Dictionary
    if let dic = NSDictionary(contentsOfFile: path) as? [String: Any] {

    }
}

Note: In Swift it is better to use Swift's generic type Array and Dictionary instead of NSArray and NSDictionary.