3 回答

TA貢獻1827條經驗 獲得超8個贊
在Swift 3.0中,從Plist讀取。
func readPropertyList() {
? ? ? ? var propertyListFormat =? PropertyListSerialization.PropertyListFormat.xml //Format of the Property List.
? ? ? ? var plistData: [String: AnyObject] = [:] //Our data
? ? ? ? let plistPath: String? = Bundle.main.path(forResource: "data", ofType: "plist")! //the path of the data
? ? ? ? let plistXML = FileManager.default.contents(atPath: plistPath!)!
? ? ? ? do {//convert the data to a dictionary and handle errors.
? ? ? ? ? ? plistData = try PropertyListSerialization.propertyList(from: plistXML, options: .mutableContainersAndLeaves, format: &propertyListFormat) as! [String:AnyObject]
? ? ? ? } catch {
? ? ? ? ? ? print("Error reading plist: \(error), format: \(propertyListFormat)")
? ? ? ? }
? ? }

TA貢獻1834條經驗 獲得超8個贊
您仍然可以在Swift中使用NSDictionaries:
對于Swift 4
var nsDictionary: NSDictionary?
if let path = Bundle.main.path(forResource: "Config", ofType: "plist") {
nsDictionary = NSDictionary(contentsOfFile: path)
}
對于Swift 3+
if let path = Bundle.main.path(forResource: "Config", ofType: "plist"),
let myDict = NSDictionary(contentsOfFile: path){
// Use your myDict here
}
和舊版的Swift
var myDict: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {
myDict = NSDictionary(contentsOfFile: path)
}
if let dict = myDict {
// Use your dict here
}
NSClasses仍然可用,并且可以在Swift中完美使用。我認為他們可能希望很快將重點轉移到swift,但是目前swift API并沒有核心NSClasses的所有功能。

TA貢獻1828條經驗 獲得超6個贊
如果我要將.plist轉換為Swift字典,這就是我要做的事情:
if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {
if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject> {
// use swift dictionary as normal
}
}
為Swift 2.0編輯:
if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist"), dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
// use swift dictionary as normal
}
為Swift 3.0編輯:
if let path = Bundle.main.path(forResource: "Config", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
// use swift dictionary as normal
}
- 3 回答
- 0 關注
- 837 瀏覽
添加回答
舉報