RDowns RDowns - 1 year ago 61
Swift Question

How do I extract a variable from a UITable DidSelectAtRow?

I have an instance where a user picks from a UITable. The selected record has a

and an
associated with it.

At the moment to verify the name and id are being correctly reported I am using

let tempCountryId = (self.newCountries[cellCountryId!])
print (tempCountryId)

Country(name: Optional("England"), countryId: Optional("5"))

I want to be able to store that countryId in a variable so I can repopulate my UITable with data (Football Divisions) that match the countryId '5'

How do I do this?

This is my full script:

import UIKit

class PickTeamViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var teamsTableView: UITableView!

var pickedCountryID: Int?

var selectedCellCountryTitle: String?
var cellCountryId: Int?

struct Country {
var name: String?
var countryId: String?

init(_ dictionary: [String : String]) {
self.name = dictionary["name"]
self.countryId = dictionary["id"]

struct Divisions {
var divisionName: String?
var divisionId: String?
init(_ dictionary: [String : String]) {

self.divisionName = dictionary["name"]
self.divisionId = dictionary["country_id"]

struct Teams {
var teamName: String?
var newTeamId: String?

init(_ dictionary: [String : String]) {
self.teamName = dictionary["name"]


struct TeamId {

var newTeamId: String?

init(_ dictionary: [String : String]) {
self.newTeamId = dictionary["id"]


var newCountries = [Country]()
var newDivisions = [Divisions]()
var newTeams = [Teams]()
var newTeamId = [TeamId]()

override func viewDidAppear(_ animated: Bool) {

let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/getTeams.php?");
var request = URLRequest(url:myUrl!);
request.httpMethod = "GET";

let task = URLSession.shared.dataTask(with: myUrl!) { (data: Data?, response: URLResponse?, error: Error?) in


if error != nil {

let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
print (json)

if let arr = json?["countries"] as? [[String:String]] {
self.newCountries = arr.flatMap { Country($0) }


if let arr = json?["divisions"] as? [[String:String]] {
self.newDivisions = arr.flatMap { Divisions($0) }


if let arr = json?["teams"] as? [[String:String]] {
self.newTeams = arr.flatMap { Teams($0) }


} catch{


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

return self.newCountries.count

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let country = newCountries[indexPath.row]
let cell = UITableViewCell()

cell.textLabel?.text = country.name
cell.textLabel?.font = UIFont(name: "Avenir", size: 12)
cell.textLabel?.textColor = UIColor.black
cell.backgroundColor = UIColor.white

return cell


func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

cellCountryId = indexPath.row
// print (self.newCountries[cellCountryId!])
let tempCountryId = (self.newCountries[cellCountryId!])
print (tempCountryId)

override func viewDidLoad() {

self.teamsTableView.delegate = self
self.teamsTableView.dataSource = self

// Do any additional setup after loading the view.


Answer Source

As discussed in the comments you should use another view controller to show the details. In didSelectRowAtIndexPath method take out the selected country from newCountries array and pass it to the DetailViewController.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let countryDetailsVC = self.storyboard?.instantiateViewController(withIdentifier: "CountryDetailsViewController") as! DetailViewController
    countryDetailsVC.country = selectedCountry
    present(countryDetailsVC, animated: true, completion: nil)

Now that you have the country Struct you can show its details in the DetailViewController.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download