Swift - read plist file to an array?

Miguel picture Miguel · Apr 23, 2016 · Viewed 15.4k times · Source

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?

enter image description here

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

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

        }
    }
}

Answer

Paul Linsay picture Paul Linsay · Mar 25, 2018

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.