Angel Davila
Angel Davila

Reputation: 75

How to use two-dimensions array in Swift?

So I have this array var arrayItinerario: Array<Any> = [] which is intended to hold arrays of type Itinerario, var temporalArray: Array<Itinerario> = []

Next, this arrayItinerario would later be used to access properties from the struct Itinerario from where the array temporalArray type comes from.

cell.siteLabel.text = "\([arrayItinerario[indexPath.section]][indexPath.row].ubicacion)"

The problem is that arrayItinerario is not an Itinerario type object which make it impossible to access ubicacion to make an example I have tried let object = [arrayItinerario[indexPath.section]][indexPath.row] as! Itinerario But the cast throws an error. How can I do to access properties from the arrays temporalArraythat are inside arrayItinerario?

Note: I am using indexPath because I am filling table cells


Upvotes: 0

Views: 229

Answers (2)

Leo Chen
Leo Chen

Reputation: 340

var arrayItinerario: [[Itinerario]] = []

//fill data
var temporalArray: [Itinerario] = []
arrayItinerario.append(temporalArray)

cell.siteLabel.text = "\(arrayItinerario[indexPath.section][indexPath.row].ubicacion)"

or

var arrayItinerario: Array<Any> = []
var temporalArray: Array<Itinerario> = []

guard let temp = arrayItinerario[indexPath.section] as? Array<Itinerario>{
    return
}

cell.siteLabel.text = "\(temp[indexPath.row].ubicacion)"

Upvotes: 1

danielbeard
danielbeard

Reputation: 9149

Here's an implementation I've used in a few projects:

import Foundation

class Array2D<T> {

    var cols:Int, rows:Int
    var matrix:[T?]

    init(cols: Int, rows: Int, defaultValue:T?) {
        self.cols = cols
        self.rows = rows
        matrix = Array(repeating: defaultValue, count: cols*rows)
    }

    subscript(col:Int, row:Int) -> T? {
        get{
            return matrix[cols * row + col]
        }
        set{
            matrix[cols * row + col] = newValue
        }
    }

    func colCount() -> Int { self.cols }
    func rowCount() -> Int { self.rows }
}

Because it's generic you can store whatever type you like in it. Example for Ints:

// Create 2D array of Ints, all set to nil initially
let arr = Array2D<Int>(cols: 10, rows: 10, defaultValue: nil)

Upvotes: 1

Related Questions