While working on the XCode projects, we usually use the “.plist” file. The property lists file stores basic data in form of key-value pairs. We can use a plist in our iOS apps as a simple key-value data store. In this blog, let’s find out what is a plist file and how to read the data on it.
What is a plist file?
A plist or property list is an XML file containing data in form of key-value pairs. Just line a dictionary in the Swift, so it’s a list of values associated with keys. In Xcode, you can open the plist’s XML structure by right-clicking on a property list file, then choosing Open As → Source Code.
A property list can contain arrays, dictionaries, booleans, dates, Data, and numbers, as integers or float.
Reading a Plist with Swift
Property lists are best to save simple, static key-value data in your app. You can read a property list file as follows:
1 2 3 4 5 6 7 8 9 10 |
func getPlist(withName name: String) -> [String]? { if let path = Bundle.main.path(forResource: name, ofType: “plist”), let xml = FileManager.default.contents(atPath: path) { let plistData = try? PropertyListSerialization.propertyList(from: xml, options: .mutableContainersAndLeaves, format: nil) return (plistData) as? [String] } return nil } |
We can use this method as follow:
1 2 3 |
if let data = getPlist(withName: “Name”) { print(data) } |
What happens in the code?
- First, we’re using optional binding to get the path of the .plist file and read the data from that file into the XML constant. If any of these two lines fail, path or XML are nil, and the conditional won’t execute.
- Then, inside the conditional, we’re deserializing the data from XML as a PropertyList. The property list is returned as an array, but we’ll have to cast it to [String] because propertyList(from: options: format: ) returns Any.
- When the conditional fails, or the typecasting fails, or the propertyList(from: options: format: ) call throws an error, the function returns nil. Else it returns an array of type [String]?, so when we call getPlist(withName:) we’re using optional binding again to get the non-optional array fruits.
Conclusion
In conclusion, we discussed how we can real a plist or propertyList file using swift. I hope this blog will help you with reading a plist file using swift. You can read more about propertyList file from here.
You can read more of my blog from here.