Swift - read plist file to an array?

后端 未结 5 1841
忘掉有多难
忘掉有多难 2021-02-08 10:55

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 thi

5条回答
  •  南旧
    南旧 (楼主)
    2021-02-08 11:40

    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.

    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]
    }()
    

提交回复
热议问题