Skip to content

Instantly share code, notes, and snippets.

@syou007
Created November 29, 2016 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syou007/2c6005e547836c2e53ac819fb3dc852d to your computer and use it in GitHub Desktop.
Save syou007/2c6005e547836c2e53ac819fb3dc852d to your computer and use it in GitHub Desktop.
Swiftでplistへアクセスする便利クラスを作った。 ref: http://qiita.com/syou007/items/2a7e09e018ef3eaf3e2f
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
}
}
let plist = Plist(name: "hoge.plst")
let str:String = plist.get("Foo") # 左辺でStringを期待して待つ。
# str = "Test"
let plist = Plist(name: "hoge.plst")
let list:[String] = plist.get("Foo.List")
for str in list {
print("str")
}
Root
Foo:Dictionary
List:Array
item0:String = "Test1"
item1:String = "Test2"
item2:String = "Test3"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment