LoginSignup
3
3

More than 5 years have passed since last update.

Swiftでplistへアクセスする便利クラスを作った。

Posted at

ジェネリクスが便利だなーと思ってplistへアクセスするクラスを作った。

class Plist {

    private var plist:NSMutableDictionary

    init(name:String) {
        let filePath = Bundle.main.path(forResource: name, ofType: nil)!
        let plist = NSMutableDictionary(contentsOfFile: filePath)!
        self.plist = plist
    }

    // データを取得します。
    func get<T>(_ key:String) -> T {
        return processing(self.plist.value(forKeyPath: key)) as! T
    }

    // get?としたかった。
    func want<T>(_ key:String) -> T? {
        return processing(self.plist.value(forKeyPath: key)) as? T
    }

    // 共通加工処理
    private func processing<T>(_ value:T?) -> T? {
        // 例) 改行コードが入っている場合は改行する。
        if let str = value as? String {
            return str.replacingOccurrences(of: "¥n", with: "\n") as? T
        }
        return value
    }
}

使い方。

hoge.plist
Root
  Foo:String = "Test"
let plist = Plist(name: "hoge.plst")
let str:String = plist.get("Foo") # 左辺でStringを期待して待つ
# str = "Test"

複雑なのも取得可能

hoge.plist
Root
  Foo:Dictionary
    List:Array
      item0:String = "Test1"
      item1:String = "Test2"
      item2:String = "Test3"
let plist = Plist(name: "hoge.plst")
let list:[String] = plist.get("Foo.List")
for str in list {
    print("str")
}

最後に

SwiftにはYamlが無くて不便だなーと思ってPlistを敬遠してたんだけど、使ってみると結構便利だった。
ただ、改行コードを入れるためには小細工(コピペや直編集)をしないと使えないところは少し微妙。

こういう型が分からない時のジェネリクスは便利だな。
alamofireでHTTPリクエストしている時にも思ったけれど。

3
3
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
3
3