Created
November 29, 2016 13:57
-
-
Save syou007/2c6005e547836c2e53ac819fb3dc852d to your computer and use it in GitHub Desktop.
Swiftでplistへアクセスする便利クラスを作った。 ref: http://qiita.com/syou007/items/2a7e09e018ef3eaf3e2f
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let plist = Plist(name: "hoge.plst") | |
let str:String = plist.get("Foo") # 左辺でStringを期待して待つ。 | |
# str = "Test" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let plist = Plist(name: "hoge.plst") | |
let list:[String] = plist.get("Foo.List") | |
for str in list { | |
print("str") | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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