How to Parse Property Lists with Swift 3

Property Lists are an easy place to save data outside of your code, for your own convenience but also to make your app or game more flexible. Leaving your Swift classes to just handle the logic behind the data the property list provides. For example, you might store level-specific settings, like how strongly the gravity affects the player. Property lists can store Arrays, Dictionaries, Data, Number, Bool and String types.

The first thing you need to do is create a Property List file for your app. Go to File > New > File… and in the Filter field you can type in “property” to quickly find a new Property List to create. In our example, it is named GameData.plist (this example partially comes from CartoonSmart.com’s recent video tutorial series on Role Playing Games with Sprite Kit and Swift 3)

Getting Data from the Property List

When retrieving data from the plist, we begin like so…

1

2

3

4

5

6

7

8

9

10

11

12

13

14

let path=Bundle.main.path(forResource:"GameData",ofType:"plist")

let dict:NSDictionary=NSDictionary(contentsOfFile:path!)!

//check to see if there is any object with the key of "Lives"

if(dict.object(forKey:"Lives")!=nil){

//next, check to see if we can create a variable named someInt that is of type Int

// use a for loop to iterate through all the keys and values in side the "Levels" dictionary...

for(key,value)inlevelDict{

//if we find a key named whatever we care about, we can print out the value....

if(key=="Whatever"){

print(value)

}

}

}

}

The only part that might be confusing is where you see [String : Any] . In Swift 3 this is one way of checking to see if a type is a Dictionary. So instead of typing Dictionary, we write [String : Any]. Using this we could test to see if the Dictionary’s keys are of String type and the values are Any (anything). When parsing a property list your keys are only ever going to be String.