Swift - 将plist文件读取到数组?

时间:2021-12-12 11:15:44

I have created a mini translation from English words to Spanish words. I would like to use the englishArray.plist instead of my englishArray = ["the cat"] How can I create this?

我创建了一个从英语单词到西班牙语单词的迷你翻译。我想使用englishArray.plist而不是我的englishArray = [“猫”]我怎样才能创建这个?

Swift  - 将plist文件读取到数组?

I have also used a localizable.strings to retrieve the value "the cat" for "el gato" but I would like to retrieve this from englishArray.plist

我还使用了localizable.strings来检索“el gato”的值“cat”但是我想从englishArray.plist中检索它

I started off with this but not sure if I'm on the right path

我从这开始,但不确定我是否在正确的道路上

let path = NSBundle.mainBundle().pathForResource("englishArray", ofType: "plist") 
let plistEnglishArray = NSArray(contentsOfFile: path!)

Here is the rest of my code:

这是我的其余代码:

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

        }
    }
}

5 个解决方案

#1


6  

Change your root object to Array, then

然后将根对象更改为Array

var myEnglishArray: [String] = []
if let URL = NSBundle.mainBundle().URLForResource("englishArray", withExtension: "plist") {
      if let englishFromPlist = NSArray(contentsOfURL: URL) as? [String] {
        for myEnglish in englishFromPlist {
          myEnglishArray.append(myEnglish)
        }
      }
    }

#2


3  

Swift 4

You can use Codable which is pure swift type.

你可以使用纯粹的swift类型的Codable。

Firstly load Plist file from bundle then use PropertyListDecoder

首先从bundle加载Plist文件然后使用PropertyListDecoder

Complete code -

完整代码 -

    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)

    }
}

#3


2  

Swift 4

The absolute simplest way to do this is

绝对最简单的方法是

    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)

The object myPlist is an Array or Dictionary, whichever you used as the base of your plist.

对象myPlist是一个数组或字典,无论你用作plist的基础。

#4


0  

This will read a resource in your bundle with the name "englishArray.plist" and store it in the immutable variable english. It will be an Optional that you should test before using.

这将读取包中名为“englishArray.plist”的资源,并将其存储在不可变变量english中。在使用之前,您应该测试它是可选的。

It uses a closure to read the file and return the array, this lets you use a immutable value rather than a mutable variable that can be changed. It's a good idea to use immutables wherever you can - they promote stability.

它使用闭包来读取文件并返回数组,这使您可以使用不可变值而不是可以更改的可变变量。在任何地方使用不可变项都是一个好主意 - 它们可以提升稳定性。

import Foundation

let english:[String]? = {
  guard let URL = NSBundle
    .mainBundle()
    .URLForResource("englishArray", withExtension: "plist") else {
      return nil
  }
  return NSArray(contentsOfURL: URL) as? [String]
}()

#5


0  

Here is the solution for swift 3. For this solution you do not need to change types in your plist structure (keep Dictionary, Array, as is). Also note that since your array's name in plist is also englishArray so the (value for key) argument in the second if statement is also englishArray.

以下是swift 3的解决方案。对于此解决方案,您无需更改plist结构中的类型(保持Dictionary,Array,按原样)。另请注意,由于plist中的数组名称也是englishArray,因此第二个if语句中的(key for key)参数也是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)
         }
      }
   }

#1


6  

Change your root object to Array, then

然后将根对象更改为Array

var myEnglishArray: [String] = []
if let URL = NSBundle.mainBundle().URLForResource("englishArray", withExtension: "plist") {
      if let englishFromPlist = NSArray(contentsOfURL: URL) as? [String] {
        for myEnglish in englishFromPlist {
          myEnglishArray.append(myEnglish)
        }
      }
    }

#2


3  

Swift 4

You can use Codable which is pure swift type.

你可以使用纯粹的swift类型的Codable。

Firstly load Plist file from bundle then use PropertyListDecoder

首先从bundle加载Plist文件然后使用PropertyListDecoder

Complete code -

完整代码 -

    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)

    }
}

#3


2  

Swift 4

The absolute simplest way to do this is

绝对最简单的方法是

    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)

The object myPlist is an Array or Dictionary, whichever you used as the base of your plist.

对象myPlist是一个数组或字典,无论你用作plist的基础。

#4


0  

This will read a resource in your bundle with the name "englishArray.plist" and store it in the immutable variable english. It will be an Optional that you should test before using.

这将读取包中名为“englishArray.plist”的资源,并将其存储在不可变变量english中。在使用之前,您应该测试它是可选的。

It uses a closure to read the file and return the array, this lets you use a immutable value rather than a mutable variable that can be changed. It's a good idea to use immutables wherever you can - they promote stability.

它使用闭包来读取文件并返回数组,这使您可以使用不可变值而不是可以更改的可变变量。在任何地方使用不可变项都是一个好主意 - 它们可以提升稳定性。

import Foundation

let english:[String]? = {
  guard let URL = NSBundle
    .mainBundle()
    .URLForResource("englishArray", withExtension: "plist") else {
      return nil
  }
  return NSArray(contentsOfURL: URL) as? [String]
}()

#5


0  

Here is the solution for swift 3. For this solution you do not need to change types in your plist structure (keep Dictionary, Array, as is). Also note that since your array's name in plist is also englishArray so the (value for key) argument in the second if statement is also englishArray.

以下是swift 3的解决方案。对于此解决方案,您无需更改plist结构中的类型(保持Dictionary,Array,按原样)。另请注意,由于plist中的数组名称也是englishArray,因此第二个if语句中的(key for key)参数也是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)
         }
      }
   }