Swift - 将 plist 文件读取到数组?
Swift - read plist file to an array?
我创建了一个从英语单词到西班牙语单词的迷你翻译。我想使用 englishArray.plist 而不是我的 englishArray = ["the cat"] 如何创建它?
我还使用 localizable.strings 检索 "el gato" 的值 "the cat",但我想从 englishArray.plist
检索该值
我从这个开始,但不确定我是否走在正确的道路上
let path = NSBundle.mainBundle().pathForResource("englishArray", ofType: "plist")
let plistEnglishArray = NSArray(contentsOfFile: path!)
这是我的其余代码:
var englishArray: [String] = ["rainbow", "boots", "heart", "leaf", "umbrella", "tired", "angry", "cry", "the cat" ]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.translateTextField.delegate = self
picker.delegate = self
picker.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func translateButtonTapped(sender: UIButton) {
let emptyString = self.translateTextField.text
if (emptyString!.isEmpty) {
print("please enter a word")
}
for transIndex in englishArray.indices {
if englishArray[transIndex] == emptyString!.lowercaseString {
//englishArray
//translateLabel.text = "\(spanishArray[transIndex])"
translateLabel.text = NSLocalizedString(emptyString!.lowercaseString, comment:"")
print(emptyString)
return
}
}
}
将您的 root
对象更改为 Array
,然后
var myEnglishArray: [String] = []
if let URL = NSBundle.mainBundle().URLForResource("englishArray", withExtension: "plist") {
if let englishFromPlist = NSArray(contentsOfURL: URL) as? [String] {
myEnglishArray = englishFromPlist
}
}
这将读取您的包中名为 "englishArray.plist" 的资源,并将其存储在不可变变量 english
中。这将是一个可选的,您应该在使用前进行测试。
它使用闭包来读取文件和 return 数组,这使您可以使用不可变值而不是可以更改的可变变量。尽可能使用不可变变量是个好主意 - 它们可以提高稳定性。
import Foundation
let english:[String]? = {
guard let URL = NSBundle
.mainBundle()
.URLForResource("englishArray", withExtension: "plist") else {
return nil
}
return NSArray(contentsOfURL: URL) as? [String]
}()
这是 swift 3 的解决方案。对于此解决方案,您不需要更改 plist 结构中的类型(保持字典、数组原样)。另请注意,由于您的数组在 plist 中的名称也是 englishArray,因此第二个 if 语句中的(键值)参数也是 englishArray。
var myEnglishArray: [String] = []
if let URL = Bundle.main.url(forResource: "englishArray", withExtension: "plist") {
guard let englishFromPlist = NSDictionary(contentsOf: URL) else { return [] }
if let englishArray = englishFromPlist.value(forKey: "englishArray") as? [String] {
for myEnglish in englishArray {
myEnglishArray.append(myEnglish)
}
}
}
Swift 4
您可以使用纯 swift 类型的 Codable。
首先从bundle
加载Plist文件然后使用PropertyListDecoder
完整代码-
func setData() {
// location of plist file
if let settingsURL = Bundle.main.path(forResource: "JsonPlist", ofType: "plist") {
do {
var settings: MySettings?
let data = try Data(contentsOf: URL(fileURLWithPath: settingsURL))
let decoder = PropertyListDecoder()
settings = try decoder.decode(MySettings.self, from: data)
print("array is \(settings?.englishArray ?? [""])")//prints array is ["Good morning", "Good afternoon"]
} catch {
print(error)
}
}
}
}
struct MySettings: Codable {
var englishArray: [String]?
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
englishArray = try values.decodeIfPresent([String].self, forKey: .englishArray)
}
}
Swift 4
最简单的方法是
let url = Bundle.main.url(forResource: "Sounds", withExtension: "plist")!
let soundsData = try! Data(contentsOf: url)
let myPlist = try! PropertyListSerialization.propertyList(from: soundsData, options: [], format: nil)
对象 myPlist 是数组或字典,以您用作 plist 的基础为准。
我创建了一个从英语单词到西班牙语单词的迷你翻译。我想使用 englishArray.plist 而不是我的 englishArray = ["the cat"] 如何创建它?
我还使用 localizable.strings 检索 "el gato" 的值 "the cat",但我想从 englishArray.plist
检索该值我从这个开始,但不确定我是否走在正确的道路上
let path = NSBundle.mainBundle().pathForResource("englishArray", ofType: "plist")
let plistEnglishArray = NSArray(contentsOfFile: path!)
这是我的其余代码:
var englishArray: [String] = ["rainbow", "boots", "heart", "leaf", "umbrella", "tired", "angry", "cry", "the cat" ]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.translateTextField.delegate = self
picker.delegate = self
picker.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func translateButtonTapped(sender: UIButton) {
let emptyString = self.translateTextField.text
if (emptyString!.isEmpty) {
print("please enter a word")
}
for transIndex in englishArray.indices {
if englishArray[transIndex] == emptyString!.lowercaseString {
//englishArray
//translateLabel.text = "\(spanishArray[transIndex])"
translateLabel.text = NSLocalizedString(emptyString!.lowercaseString, comment:"")
print(emptyString)
return
}
}
}
将您的 root
对象更改为 Array
,然后
var myEnglishArray: [String] = []
if let URL = NSBundle.mainBundle().URLForResource("englishArray", withExtension: "plist") {
if let englishFromPlist = NSArray(contentsOfURL: URL) as? [String] {
myEnglishArray = englishFromPlist
}
}
这将读取您的包中名为 "englishArray.plist" 的资源,并将其存储在不可变变量 english
中。这将是一个可选的,您应该在使用前进行测试。
它使用闭包来读取文件和 return 数组,这使您可以使用不可变值而不是可以更改的可变变量。尽可能使用不可变变量是个好主意 - 它们可以提高稳定性。
import Foundation
let english:[String]? = {
guard let URL = NSBundle
.mainBundle()
.URLForResource("englishArray", withExtension: "plist") else {
return nil
}
return NSArray(contentsOfURL: URL) as? [String]
}()
这是 swift 3 的解决方案。对于此解决方案,您不需要更改 plist 结构中的类型(保持字典、数组原样)。另请注意,由于您的数组在 plist 中的名称也是 englishArray,因此第二个 if 语句中的(键值)参数也是 englishArray。
var myEnglishArray: [String] = []
if let URL = Bundle.main.url(forResource: "englishArray", withExtension: "plist") {
guard let englishFromPlist = NSDictionary(contentsOf: URL) else { return [] }
if let englishArray = englishFromPlist.value(forKey: "englishArray") as? [String] {
for myEnglish in englishArray {
myEnglishArray.append(myEnglish)
}
}
}
Swift 4
您可以使用纯 swift 类型的 Codable。
首先从bundle
加载Plist文件然后使用PropertyListDecoder
完整代码-
func setData() {
// location of plist file
if let settingsURL = Bundle.main.path(forResource: "JsonPlist", ofType: "plist") {
do {
var settings: MySettings?
let data = try Data(contentsOf: URL(fileURLWithPath: settingsURL))
let decoder = PropertyListDecoder()
settings = try decoder.decode(MySettings.self, from: data)
print("array is \(settings?.englishArray ?? [""])")//prints array is ["Good morning", "Good afternoon"]
} catch {
print(error)
}
}
}
}
struct MySettings: Codable {
var englishArray: [String]?
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
englishArray = try values.decodeIfPresent([String].self, forKey: .englishArray)
}
}
Swift 4
最简单的方法是
let url = Bundle.main.url(forResource: "Sounds", withExtension: "plist")!
let soundsData = try! Data(contentsOf: url)
let myPlist = try! PropertyListSerialization.propertyList(from: soundsData, options: [], format: nil)
对象 myPlist 是数组或字典,以您用作 plist 的基础为准。