简体   繁体   中英

Swift: How to access specific data from struct inside an array?

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let  cell = UITableViewCell(style: .default, reuseIdentifier: nil)
    
    text_here?.text = data[indexPath.row].properties.timeseries.description
    
    return cell

}

struct Properties: Decodable {
let meta: Meta
var timeseries: [Timeseries]

}

struct Timeseries: Decodable {
let time: String
let data: Data

}

struct Data: Decodable {
    let instant: Instant
   // let next_1_hours: Next_1_hours
    //let next_6_hours: Next_6_hours
    //let next_12_hours: Next_12_hours

}

struct Instant: Decodable {
    let details: Details
}

// MARK: - Details
struct Details: Decodable {
    let air_pressure_at_sea_level: Double
    let air_temperature: Double
    let cloud_area_fraction: Double?
    let cloud_area_fraction_high: Double?
    let cloud_area_fraction_low: Double?
    let cloud_area_fraction_medium: Double?
    let dew_point_temperature: Double?
    let fog_area_fraction: Double?
    let relative_humidity: Double
    let ultraviolet_index_clear_sky: Double?
    let wind_from_direction: Double
    let wind_speed: Double
}

On this code line "text_here?.text = data[indexPath.row].properties.timeseries.description". I can't specify further like; "text_here?.text = data[indexPath.row].properties.timeseries.data.instant.details.air_pressure_at_sea_level.description".

So my question is how do I attend the data declared in a array, so i can specify the data behind it? Like in the code example over.

Try out subscripting the timeseries array first

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let  cell = UITableViewCell(style: .default, reuseIdentifier: nil)
    
    text_here?.text = data[indexPath.row].properties.timeseries[*index*]..
    
    return cell

from Structures and Classes

struct Resolution {
    var width = 0
    var height = 0
}
let someResolution = Resolution()
print("The width of someResolution is \(someResolution.width)")
// Prints "The width of someResolution is 0"

This is how you declare a struct, initialize it and access it's properties. You can store structs of the same type in an Collection Types , and then access elements using an index.

let resolutions = [Resolution]()
resolutions.append(someResolution)
let myResolutionWidth = resolutions[0].width

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM