如何在Swift中将plist作为字典?


197

我在玩苹果的新Swift编程语言时遇到了一些问题...

当前,我正在尝试读取plist文件,在Objective-C中,我将执行以下操作以将内容作为NSDictionary获取:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:filePath];

如何在Swift中将plist作为字典?

我假设我可以通过以下方式获得plist的路径:

let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist")

当这可行时(如果正确的话?):如何将内容作为字典?

还有一个更笼统的问题:

是否可以使用默认的NS *类?我想是...还是我错过了什么?据我所知,默认框架NS *类仍然有效并且可以使用吗?


答案不再有效,能否请您选择Ashok的答案?
RodolfoAntonici

Answers:


51

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)")
        }
    }

阅读更多 如何在SWIFT中使用属性列表(.PLIST)


阿斯克 今天就花了很多时间试图为此找到答案!谢谢!!这工作得很好!!!
user3069232'3

281

您仍然可以在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的所有功能。


嗯,当我尝试使用您提供的代码时,出现错误:xxx没有名为dict的成员
KennyVB 2014年

它在游乐场都可以正常工作。只是不在我的快速文档中
KennyVB 2014年

如果是Array,它看起来如何?
2014年

像看起来mainBundle()只是main在斯威夫特3
BallpointBen

8
这个答案已经过时了。即使在Swift 3中,您也不应该使用它NSArray/NSDictionary来读取属性列表数据。PropertyListSerialization(以及Swift 4中的Codable协议)是合适的API。它提供了现代的错误处理,并且可以将数据直接转换为本机Swift集合类型。
vadian

141

如果我要将.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
我认为这是一堆“最正确”的答案,除非有一种本机迅速的方法可以做到。
DudeOnRock 2014年

1
这个答案已经过时了。在Swift 3中,您根本不应该使用NSArray/NSDictionary读取属性列表数据。PropertyListSerialization(以及Swift 4中的Codable协议)是合适的API。它提供了现代的错误处理,并且可以将数据直接转换为本机Swift集合类型。
vadian

47

迅捷4.0

现在,您可以使用Decodable协议将.plist解码为自定义结构。我将介绍一个基本示例,有关更复杂的.plist结构,我建议阅读Decodable / Encodable(此处提供了很好的资源:https ://benscheirman.com/2017/06/swift-json/ )。

首先将您的结构设置为.plist文件的格式。对于此示例,我将考虑一个具有根级别Dictionary和3个条目的.plist:1个具有键“ name”的字符串,1个具有键“ age”的Int和1个具有键“ single”的Boolean。这是结构:

struct Config: Decodable {
    private enum CodingKeys: String, CodingKey {
        case name, age, single
    }

    let name: String
    let age: Int
    let single: Bool
}

很简单。现在很酷的部分。使用PropertyListDecoder类,我们可以轻松地将.plist文件解析为该结构的实例:

func parseConfig() -> Config {
    let url = Bundle.main.url(forResource: "Config", withExtension: "plist")!
    let data = try! Data(contentsOf: url)
    let decoder = PropertyListDecoder()
    return try! decoder.decode(Config.self, from: data)
}

不用担心更多的代码,所有这些都在Swift中。更好的是,我们现在可以轻松使用Config结构的实例化:

let config = parseConfig()
print(config.name) 
print(config.age)
print(config.single) 

这将打印.plist中“名称”,“年龄”和“单个”键的值。


1
这是Swift 4的最佳答案。但是为什么不Bundle.main.url(forResource: "Config", withExtension: "plist")摆脱它URL(fileURLWithPath呢?并且由于文件必须存在(在设计/编译时),所有值都可以强制展开。如果一切设计正确,则代码不得崩溃。
vadian

@vadian确保可以使用,url(forResource: "Config", withExtension: "plist")我只是将OP在其代码中所做的作为匹配点。至于用力解开一切,我会谨慎地尝试犯错。我认为这通常是Swift的基本问题。我宁愿确切地知道我的代码在任何情况下都会做什么,而不是崩溃。
ekreloff

1)如果有更合适的API,请不要养成不良习惯。2)这是在少数情况下强制崩溃发现设计错误的情况之一。捆绑软件中的任何文件都必须在编译时存在,并且在运行时不能更改,因为所有文件都是代码签名的。再一次:如果一切设计正确,则代码不会崩溃
vadian

是的,你知道你的权利。没意识到捆绑资源就是这种情况。
ekreloff

2
@NaveenGeorgeThoppan如果使用此示例作为字典,则它将简单地为decoder.decode([Config].self, from: data)。(注意[Config]周围的括号)
ekreloff

22

此答案使用Swift本机对象而不是NSDictionary。

斯威夫特3.0

//get the path of the plist file
guard let plistPath = Bundle.main.path(forResource: "level1", ofType: "plist") else { return }
//load the plist as data in memory
guard let plistData = FileManager.default.contents(atPath: plistPath) else { return }
//use the format of a property list (xml)
var format = PropertyListSerialization.PropertyListFormat.xml
//convert the plist data to a Swift Dictionary
guard let  plistDict = try! PropertyListSerialization.propertyList(from: plistData, options: .mutableContainersAndLeaves, format: &format) as? [String : AnyObject] else { return }
//access the values in the dictionary 
if let value = plistDict["aKey"] as? String {
  //do something with your value
  print(value)
}
//you can also use the coalesce operator to handle possible nil values
var myValue = plistDict["aKey"] ?? ""

是否有一个简洁的版本?
harsh_v

18

我一直在使用Swift 3.0,并希望为更新的语法提供答案。另外,可能更重要的是,我正在使用PropertyListSerialization对象进行繁重的工作,这比仅使用NSDictionary灵活得多,因为它允许将Array用作plist的根类型。

以下是我正在使用的plist的屏幕截图。为了显示可用的功能,它有点复杂,但这对于plist类型的任何允许组合都适用。

示例plist文件 如您所见,我正在使用String:String字典数组存储网站名称及其对应URL的列表。

如上所述,我正在使用PropertyListSerialization对象为我完成繁重的工作。另外,Swift 3.0变得更加“ Swifty”,因此所有对象名称都丢失了“ NS”前缀。

let path = Bundle.main().pathForResource("DefaultSiteList", ofType: "plist")!
let url = URL(fileURLWithPath: path)
let data = try! Data(contentsOf: url)
let plist = try! PropertyListSerialization.propertyList(from: data, options: .mutableContainers, format: nil)

在上面的代码运行之后plist将是类型Array<AnyObject>,但是我们知道它实际上是什么类型,因此我们可以将其转换为正确的类型:

let dictArray = plist as! [[String:String]]
// [[String:String]] is equivalent to Array< Dictionary<String, String> >

现在,我们可以自然地访问String:String Dictionaries数组的各种属性。希望将它们转换为实际的强类型结构或类;)

print(dictArray[0]["Name"])

8

最好使用本机字典和数组,因为它们已针对使用swift进行了优化。话虽如此,您可以快速使用NS ...类,我认为这种情况值得证明。这是实现它的方法:

var path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist")
var dict = NSDictionary(contentsOfFile: path)

到目前为止(在我看来),这是访问plist的最简单,最有效的方法,但是将来,我希望Apple可以在本机词典中添加更多功能(例如使用plist)。


据您所知,已经在本地字典中添加了plist阅读功能吗?
SpacyRicochet 2015年

8

Swift-读取/写入plist和文本文件。

override func viewDidLoad() {
    super.viewDidLoad()

    let fileManager = (NSFileManager .defaultManager())
    let directorys : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask, true) as? [String]

    if (directorys != nil){
        let directories:[String] = directorys!;
        let dictionary = directories[0]; //documents directory


        //  Create and insert the data into the Plist file  ....
        let plistfile = "myPlist.plist"
        var myDictionary: NSMutableDictionary = ["Content": "This is a sample Plist file ........."]
        let plistpath = dictionary.stringByAppendingPathComponent(plistfile);

        if !fileManager .fileExistsAtPath(plistpath){//writing Plist file
            myDictionary.writeToFile(plistpath, atomically: false)
        }
        else{            //Reading Plist file
            println("Plist file found")

            let resultDictionary = NSMutableDictionary(contentsOfFile: plistpath)
            println(resultDictionary?.description)
        }


        //  Create and insert the data into the Text file  ....
        let textfile = "myText.txt"
        let sampleText = "This is a sample text file ......... "

        let textpath = dictionary.stringByAppendingPathComponent(textfile);
        if !fileManager .fileExistsAtPath(textpath){//writing text file
            sampleText.writeToFile(textpath, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
        } else{
            //Reading text file
            let reulttext  = String(contentsOfFile: textpath, encoding: NSUTF8StringEncoding, error: nil)
            println(reulttext)
        }
    }
    else {
        println("directory is empty")
    }
}

8

Swift 2.0:访问Info.Plist

我有一个名为CoachMarksDictionary的字典,在Info.Plist中具有布尔值。我想访问布尔值并将其设为true。

let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")!
  let dict = NSDictionary(contentsOfFile: path) as! [String: AnyObject]

  if let CoachMarksDict = dict["CoachMarksDictionary"] {
       print("Info.plist : \(CoachMarksDict)")

   var dashC = CoachMarksDict["DashBoardCompleted"] as! Bool
    print("DashBoardCompleted state :\(dashC) ")
  }

写给Plist:

从自定义Plist :-(从File-New-File-Resource-PropertyList中创建。添加了三个名为DashBoard_New,DashBoard_Draft,DashBoard_Completed的字符串)

func writeToCoachMarksPlist(status:String?,keyName:String?)
 {
  let path1 = NSBundle.mainBundle().pathForResource("CoachMarks", ofType: "plist")
  let coachMarksDICT = NSMutableDictionary(contentsOfFile: path1!)! as NSMutableDictionary
  var coachMarksMine = coachMarksDICT.objectForKey(keyName!)

  coachMarksMine  = status
  coachMarksDICT.setValue(status, forKey: keyName!)
  coachMarksDICT.writeToFile(path1!, atomically: true)
 }

该方法可以称为

self.writeToCoachMarksPlist(" true - means user has checked the marks",keyName: "the key in the CoachMarks dictionary").

这就是我一直在寻找的!谢谢哥们!
Jayprakash Dubey

6

通过尼克的答案转换为便捷扩展:

extension Dictionary {
    static func contentsOf(path: URL) -> Dictionary<String, AnyObject> {
        let data = try! Data(contentsOf: path)
        let plist = try! PropertyListSerialization.propertyList(from: data, options: .mutableContainers, format: nil)

        return plist as! [String: AnyObject]
    }
}

用法:

let path = Bundle.main.path(forResource: "plistName", ofType: "plist")!
let url = URL(fileURLWithPath: path)
let dict = Dictionary<String, AnyObject>.contentsOf(path: url)

我愿意打赌,它也可以为数组创建类似的扩展


5

实际上可以在1行中完成

    var dict = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Config", ofType: "plist"))

5

您可以通过以下方式使用SWIFT语言阅读plist:

let path = NSBundle.mainBundle().pathForResource("PriceList", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path)

读取单个字典值:

let test: AnyObject = dict.objectForKey("index1")

如果要在plist中获得完整的多维词典:

let value: AnyObject = dict.objectForKey("index2").objectForKey("date")

这是plist:

<plist version="1.0">
<dict>
<key>index2</key>
<dict>
    <key>date</key>
    <string>20140610</string>
    <key>amount</key>
    <string>110</string>
</dict>
<key>index1</key>
<dict>
    <key>amount</key>
    <string>125</string>
    <key>date</key>
    <string>20140212</string>
</dict>
</dict>
</plist>

4

由于尚未找到此答案,所以只想指出,您还可以使用infoDictionary属性将info plist作为字典获取Bundle.main.infoDictionary

尽管如果您只对info plist中的特定项目感兴趣,Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String) 可能会更快一些。

// Swift 4

// Getting info plist as a dictionary
let dictionary = Bundle.main.infoDictionary

// Getting the app display name from the info plist
Bundle.main.infoDictionary?[kCFBundleNameKey as String]

// Getting the app display name from the info plist (another way)
Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String)

3

在我的情况下,我创建一个NSDictionary被调用appSettings并添加所有需要的键。对于这种情况,解决方案是:

if let dict = NSBundle.mainBundle().objectForInfoDictionaryKey("appSettings") {
  if let configAppToken = dict["myKeyInsideAppSettings"] as? String {

  }
}

谢谢。objectForInfoDictionaryKey正是我想要的。
LunaCodeGirl '16

2

您可以使用它,我在github https://github.com/DaRkD0G/LoadExtension中为Dictionary创建了一个简单的扩展

extension Dictionary {
    /**
        Load a Plist file from the app bundle into a new dictionary

        :param: File name
        :return: Dictionary<String, AnyObject>?
    */
    static func loadPlistFromProject(filename: String) -> Dictionary<String, AnyObject>? {

        if let path = NSBundle.mainBundle().pathForResource("GameParam", ofType: "plist") {
            return NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject>
        }
        println("Could not find file: \(filename)")
        return nil
    }
}

你可以用它来加载

/**
  Example function for load Files Plist

  :param: Name File Plist
*/
func loadPlist(filename: String) -> ExampleClass? {
    if let dictionary = Dictionary<String, AnyObject>.loadPlistFromProject(filename) {
        let stringValue = (dictionary["name"] as NSString)
        let intergerValue = (dictionary["score"] as NSString).integerValue
        let doubleValue = (dictionary["transition"] as NSString).doubleValue

        return ExampleClass(stringValue: stringValue, intergerValue: intergerValue, doubleValue: doubleValue)
    }
    return nil
}

2

这是一个简短的版本,基于@connor的答案

guard let path = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist"),
    let myDict = NSDictionary(contentsOfFile: path) else {
    return nil
}

let value = dict.value(forKey: "CLIENT_ID") as! String?

2

斯威夫特3.0

if let path = Bundle.main.path(forResource: "config", ofType: "plist") {
    let dict = NSDictionary(contentsOfFile: path)

    // use dictionary
}

我认为最简单的方法。


2

我创建了一个简单的Dictionary初始化器来替换NSDictionary(contentsOfFile: path)。只需删除NS

extension Dictionary where Key == String, Value == Any {

    public init?(contentsOfFile path: String) {
        let url = URL(fileURLWithPath: path)

        self.init(contentsOfURL: url)
    }

    public init?(contentsOfURL url: URL) {
        guard let data = try? Data(contentsOf: url),
            let dictionary = (try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any]) ?? nil
            else { return nil }

        self = dictionary
    }

}

您可以这样使用它:

let filePath = Bundle.main.path(forResource: "Preferences", ofType: "plist")!
let preferences = Dictionary(contentsOfFile: filePath)!
UserDefaults.standard.register(defaults: preferences)

2

基于上述https://stackoverflow.com/users/3647770/ashok-r的答案,Swift 4.0 iOS 11.2.6列出了已解析的代码并对其进行了解析。

<?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">
<array>
  <dict>
    <key>identity</key>
    <string>blah-1</string>
    <key>major</key>
    <string>1</string>
    <key>minor</key>
    <string>1</string>
    <key>uuid</key>
    <string>f45321</string>
    <key>web</key>
    <string>http://web</string>
</dict>
<dict>
    <key>identity</key>
    <string></string>
    <key>major</key>
    <string></string>
    <key>minor</key>
    <string></string>
    <key>uuid</key>
    <string></string>
    <key>web</key>
    <string></string>
  </dict>
</array>
</plist>

do {
   let plistXML = try Data(contentsOf: url)
    var plistData: [[String: AnyObject]] = [[:]]
    var propertyListFormat =  PropertyListSerialization.PropertyListFormat.xml
        do {
            plistData = try PropertyListSerialization.propertyList(from: plistXML, options: .mutableContainersAndLeaves, format: &propertyListFormat) as! [[String:AnyObject]]

        } catch {
            print("Error reading plist: \(error), format: \(propertyListFormat)")
        }
    } catch {
        print("error no upload")
    }

1

第1步:快速快捷地解析plist的简单方法3+

extension Bundle {

    func parsePlist(ofName name: String) -> [String: AnyObject]? {

        // check if plist data available
        guard let plistURL = Bundle.main.url(forResource: name, withExtension: "plist"),
            let data = try? Data(contentsOf: plistURL)
            else {
                return nil
        }

        // parse plist into [String: Anyobject]
        guard let plistDictionary = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: AnyObject] else {
            return nil
        }

        return plistDictionary
    }
}

步骤2:使用方法:

Bundle().parsePlist(ofName: "Your-Plist-Name")

0

这是我找到的解决方案:

let levelBlocks = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("LevelBlocks", ofType: "plist"))
let test: AnyObject = levelBlocks.objectForKey("Level1")
println(test) // Prints the value of test

我设置的类型test,以AnyObject沉默对可能发生的意外推断警告。

而且,它必须在类方法中完成。

要访问并保存已知类型的特定值,请执行以下操作:

let value = levelBlocks.objectForKey("Level1").objectForKey("amount") as Int
println(toString(value)) // Converts value to String and prints it

0

我使用快速字典,但在文件管理器类中将它们与NSDictionaries相互转换:

    func writePlist(fileName:String, myDict:Dictionary<String, AnyObject>){
        let docsDir:String = dirPaths[0] as String
        let docPath = docsDir + "/" + fileName
        let thisDict = myDict as NSDictionary
        if(thisDict.writeToFile(docPath, atomically: true)){
            NSLog("success")
        } else {
            NSLog("failure")
        }

    }
    func getPlist(fileName:String)->Dictionary<String, AnyObject>{
        let docsDir:String = dirPaths[0] as String
        let docPath = docsDir + "/" + fileName
        let thisDict = NSDictionary(contentsOfFile: docPath)
        return thisDict! as! Dictionary<String, AnyObject>
    }

这似乎是最不麻烦的读写方式,但让我的其余代码保持尽可能快。


0

Plist是我为处理属性列表所做的一个简单的Swift枚举。

// load an applications info.plist data

let info = Plist(NSBundle.mainBundle().infoDictionary)
let identifier = info["CFBundleIndentifier"].string!

更多示例:

import Plist

// initialize using an NSDictionary
// and retrieve keyed values

let info = Plist(dict)
let name = info["name"].string ?? ""
let age = info["age"].int ?? 0


// initialize using an NSArray
// and retrieve indexed values

let info = Plist(array)
let itemAtIndex0 = info[0].value


// utility initiaizer to load a plist file at specified path
let info = Plist(path: "path_to_plist_file")

// we support index chaining - you can get to a dictionary from an array via
// a dictionary and so on
// don't worry, the following will not fail with errors in case
// the index path is invalid
if let complicatedAccessOfSomeStringValueOfInterest = info["dictKey"][10]["anotherKey"].string {
  // do something
}
else {
  // data cannot be indexed
}

// you can also re-use parts of a plist data structure

let info = Plist(...)
let firstSection = info["Sections"][0]["SectionData"]
let sectionKey = firstSection["key"].string!
let sectionSecret = firstSection["secret"].int!

Plist.swift

Plist本身很简单,如果您直接引用,这里是它的清单。

//
//  Plist.swift
//


import Foundation


public enum Plist {

    case dictionary(NSDictionary)
    case Array(NSArray)
    case Value(Any)
    case none

    public init(_ dict: NSDictionary) {
        self = .dictionary(dict)
    }

    public init(_ array: NSArray) {
        self = .Array(array)
    }

    public init(_ value: Any?) {
        self = Plist.wrap(value)
    }

}


// MARK:- initialize from a path

extension Plist {

    public init(path: String) {
        if let dict = NSDictionary(contentsOfFile: path) {
            self = .dictionary(dict)
        }
        else if let array = NSArray(contentsOfFile: path) {
            self = .Array(array)
        }
        else {
            self = .none
        }
    }

}


// MARK:- private helpers

extension Plist {

    /// wraps a given object to a Plist
    fileprivate static func wrap(_ object: Any?) -> Plist {

        if let dict = object as? NSDictionary {
            return .dictionary(dict)
        }
        if let array = object as? NSArray {
            return .Array(array)
        }
        if let value = object {
            return .Value(value)
        }
        return .none
    }

    /// tries to cast to an optional T
    fileprivate func cast<T>() -> T? {
        switch self {
        case let .Value(value):
            return value as? T
        default:
            return nil
        }
    }
}

// MARK:- subscripting

extension Plist {

    /// index a dictionary
    public subscript(key: String) -> Plist {
        switch self {

        case let .dictionary(dict):
            let v = dict.object(forKey: key)
            return Plist.wrap(v)

        default:
            return .none
        }
    }

    /// index an array
    public subscript(index: Int) -> Plist {
        switch self {
        case let .Array(array):
            if index >= 0 && index < array.count {
                return Plist.wrap(array[index])
            }
            return .none

        default:
            return .none
        }
    }

}


// MARK:- Value extraction

extension Plist {

    public var string: String?       { return cast() }
    public var int: Int?             { return cast() }
    public var double: Double?       { return cast() }
    public var float: Float?         { return cast() }
    public var date: Date?         { return cast() }
    public var data: Data?         { return cast() }
    public var number: NSNumber?     { return cast() }
    public var bool: Bool?           { return cast() }


    // unwraps and returns the underlying value
    public var value: Any? {
        switch self {
        case let .Value(value):
            return value
        case let .dictionary(dict):
            return dict
        case let .Array(array):
            return array
        case .none:
            return nil
        }
    }

    // returns the underlying array
    public var array: NSArray? {
        switch self {
        case let .Array(array):
            return array
        default:
            return nil
        }
    }

    // returns the underlying dictionary
    public var dict: NSDictionary? {
        switch self {
        case let .dictionary(dict):
            return dict
        default:
            return nil
        }
    }

}


// MARK:- CustomStringConvertible

extension Plist : CustomStringConvertible {
    public var description:String {
        switch self {
        case let .Array(array): return "(array \(array))"
        case let .dictionary(dict): return "(dict \(dict))"
        case let .Value(value): return "(value \(value))"
        case .none: return "(none)"
        }
    }
}

0

斯威夫特3.0

如果您想从.plist读取“二维数组”,则可以这样尝试:

if let path = Bundle.main.path(forResource: "Info", ofType: "plist") {
    if let dimension1 = NSDictionary(contentsOfFile: path) {
        if let dimension2 = dimension1["key"] as? [String] {
            destination_array = dimension2
        }
    }
}

-2

访问plist文件的简单结构(Swift 2.0)

struct Configuration {      
  static let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist")!
  static let dict = NSDictionary(contentsOfFile: path) as! [String: AnyObject]

  static let someValue = dict["someKey"] as! String
}

用法:

print("someValue = \(Configuration.someValue)")
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.