LoginSignup
2
6

More than 5 years have passed since last update.

plistからデータを読み込む swift 3.0

Posted at

plistから配列を読みたい時

この場合は fruits.plist というフォルダを指定ていて、それぞれのデータを使って Fruitクラスを一個ずつ作っている。

MakeData.swift

        if let path = Bundle.main.path(forResource: "fruits", ofType: "plist") {
            if let dictArray = NSArray(contentsOfFile: path) {
                for item in dictArray {
                    if let dict = item as? NSDictionary {
                        let name = dict["name"] as! String
                        let group = dict["group"] as! String

                        let fruit = Fruit(name: name, group: group)
                        if !groups.contains(group){
                            groups.append(group)
                        }
                        fruits.append(fruit)
                    }
                }

Fruit.swift
class Fruit {
    var name:String?
    var group:String?

    init(name: String, group: String) {
        self.name = name
        self.group = group

    }
}

fruits.plistの中身はこんな感じ。

Screen Shot 2017-07-01 at 2.22.43 AM.png

@rshankrasさんのコードから参照
https://github.com/rshankras/FruitsDiet

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6