Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read plist in swift 3 playground

I have followed loads of questions here but nothing seems to work.

I am using Swift3 in a Playground. Running on El Capitan and Xcode 8.1. I have a plist with the root as a Dictionary containing one Int value and two 2D Arrays of Ints.

plist

Every question I follow does not seem to work the closest I have got is for the playground to not return errors but it seems to be constantly running (the spinning icon never stops).

my current code, I believe to be the closest I have achieved.

import Foundation 
if let path = Bundle.main.path(forResource: "levelList", ofType: "plist") {
    let plistXML = FileManager.default.contents(atPath: path)!

    let mydata = try! PropertyListSerialization.propertyList(from: plistXML, options: [], format: nil) as! [String:Any]
}

other options I have tried from previous stack overflow answers in a similar context.

let mydata = Dictionary(fromPropertyList: path, format: "XML") as! [String: Any]
******
let mydata = Dictionary(contentsOf: path) as? [String: Any]

The data was added to the resources folder correctly as the linked question gave instructions for. I have restarted Xcode(and mac) as suggested in the comments. After a while the execution stopped with error "error: Execution was interrupted reason exc_bad_access (code=1 address=0x0)" After another restart the code works. How do would i extract the data into an array in swift since at the moment the playground is showing ["Level 2":["Col": <_NS_array0 0x7fc620d091a0>(

like image 800
Andrew Avatar asked Dec 13 '25 14:12

Andrew


1 Answers

You are using the wrong API, you need to load Data rather than something in the file system.

if let url = Bundle.main.url(forResource: "levelList", withExtension: "plist"),
   let plistData = try? Data(contentsOf: url ) {
      let mydata = try! PropertyListSerialization.propertyList(from: plistData, options: [], format: nil) as! [String:Any]
}
like image 143
vadian Avatar answered Dec 15 '25 07:12

vadian