2016-11-05 1 views
0

は、私はすでにSwift 3のネイティブSwift方法をPlistで読むにはどうすればいいですか?

var myDict: NSDictionary? 
if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") { 
myDict = NSDictionary(contentsOfFile: path) 
} 

スウィフト2に、このメソッドを使用しました。しかし NSDictionaryの使用せずにSwift3でplistの読み方を知らない:

+0

ご質問はありますか?あなたは何を達成しようとしていますか? – Adeel

+0

上記のコードのためにswift3変換が必要 –

+0

私のウェブサイトhttps://ioswisdom.000webhostapp.com/ –

答えて

17

ネイティブスウィフト方法がある(contentsOfFileパス)

PropertyListSerialization

if let url = Bundle.main.url(forResource:"Config", withExtension: "plist") { 
    do { 
    let data = try Data(contentsOf:url) 
    let swiftDictionary = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [String:Any] 
     // do something with the dictionary 
    } catch { 
     print(error) 
    } 
} 

を使用するには、また、型キャストでNSDictionary(contentsOf:を使用することができます

if let url = Bundle.main.url(forResource:"Config", withExtension: "plist"), 
    let myDict = NSDictionary(contentsOf: url) as? [String:Any] { 
    print(myDict) 
} 

いますが、明示的に書いた:をNSDictionaryの(contentsOfを使用しなくても...

は基本的にあなたが重要なタイプの情報を捨てている、スウィフトにキャストせずにNSDictionaryを使用しないでください。

+0

から参照してください。ネイティブな方法で辞書を使用するには、** PropertyListSerialization **を使用する必要があります** –

+1

必ずしもそうではありません。私は答えを更新しました。 – vadian

+0

@vadian私は、 'Swift'のもとで' import foundation'がこれを動作させるために必要であると付け加えたいと思います。 – dinesharjani

関連する問題