Getting a Swift dictionary from a plist file is relatively straighforward. If you would like to get your Info.plist file in dictionary form, it can be done as a one-liner:
let infoDictionary = Bundle.main.infoDictionary
You can use this method across all of Apple's platforms. It works for iOS as well as macOS.
While Bundle.main.infoDictionary
works great for quickly getting your Info.plist file as a dictionary, what if you want to get a dictionary from any plist file? That's where the PropertyListSerialization
class from the Foundation framework comes in handy.
let plistString = """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>key1</key>
<string>value1</string>
</dict>
</plist>
"""
let plistData = plistString.data(using: .utf8)
do {
if let plist = try PropertyListSerialization.propertyList(from: plistData!, format: nil)
as? [String: Any] {
print(plist)
} else {
print("Not able to convert plist to dictionary")
}
} catch let error {
print(error)
}
In the above code snippet, we take a plist string and convert it to data using the string's .data()
method. Then we use the PropertyListSerialization
class to convert the data to a dictionary.