mardi 23 juin 2015

How to populate an array from a .txt file in Swift

So a bit on the background:

I have a VC, with a textField, when pressed, the user is segued to a tableView controller. The idea is, they need to tell me the country they are from. So I currently have an array, which holds some countries in, and then this is populated into the tableView. All works fine. But, I need to display all the countries, and as there are like 196 countries, i thought it would be silly to have an array with 196 countries in.

Is there a way i can create a .txt file with all the countries in, and then populate the array from this .txt file? I have made a file called: Countries.txt and it's currently blank.

  1. How do I write the list of countries in the .txt file? e.g. "France" "Spain" "United Kingdom" "United States" - do I need to use a comma to separate them?

  2. What code do I need to write in the tableViewController.swift to make this work?

  3. Or, is there a better way I can do this?

Thanks in advance, I'm very new to swift so please go easy :)

My code for tableViewController:

import UIKit

class TableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating {

@IBOutlet var tabeView: UITableView!

var countryPicker = ["Colombia", "England", "France", "Germany", "Brazil", "Austria", "Spain", "Australia", "USA", "Berlin", "Thailand", "Northern Ireland", "New Zealand", "Hawaii", "Switzerland", "Sweeden", "Finland", "Turkey", "Russia", "Netherlands", "Japan"]


override func viewDidLoad() {
    super.viewDidLoad()

    countryPicker.sort(){$0 < $1}

}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return 1

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return countryPicker.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath) as! UITableViewCell

    cell.textLabel?.text = countryPicker[indexPath.row]

    return cell
}

See more ..

Aucun commentaire:

Enregistrer un commentaire