IOS 8 Swift Read Plist

I want to read values ​​from plist file as integers. I have the following code:

let path = NSBundle.mainBundle().pathForResource("savedState", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)
let players: AnyObject = String(dict.valueForKey("players") as NSString)
let level: AnyObject = String(dict.valueForKey("level") as NSString)
let numPlayers = Int(players as NSNumber)
let playLevel = Int(level as NSNumber)

      

Let the players: and let the level: crash my app. I know this should be easy - I just can't figure out how to do it.

+3


source to share


1 answer


You may be looking for something like this:

let path = NSBundle.mainBundle().pathForResource("savedState", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)
let players = dict.valueForKey("players") as? String
let level = dict.valueForKey("level") as? String
let numPlayers = players != nil ? players!.toInt() : 0
let playLevel = level != nil ? level!.toInt() : 0

      



It tries to read the players and the level from the plist as optional strings, then if they are not null, it sets numPlayers and playLevel to Int. If they are nil numPlayers and playLevel are set to 0. Although, if your plist values ​​are integers, why not just read them as Ints?

let players = dict.valueForKey("players") as? Int
let level = dict.valueForKey("level") as? Int 

      

+7


source







All Articles