adman adman - 1 month ago 5x
Swift Question

Swift - error "Cannot subscript a value of '[String: DayData]' with an index of tye 'Int'

So I'm trying to create a table view that will take information from a source I've already concocted in a different view controller. I'm having some trouble when I try to pull the information into the cells of the table view.

I'm getting the error "Cannot subscript a value of '[String: DayData]' with an index of tye 'Int'" on the line that starts with "var (date, sales, doorsKnocked..."

I'm not sure how to fix this. Can anyone figure it out? Thanks!

import Foundation
import UIKit

var allInformationByDate = [
"2016-08-13": DayData(sales: 0, doorsKnocked: 0, milesWalked: 0.00, hoursWorked: 0.00)

struct DayData {
let sales: Int
let doorsKnocked: Int
let milesWalked: Double
let hoursWorked: Double

class historyViewController: UIViewController, UITableViewDataSource {

//return Int, how many sections in table
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1

//return Int, how many rows in table
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allInformationByDate.count

//what are the contents of each cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()

var (date, sales, doorsKnocked, milesWalked, hoursWorked) = allInformationByDate[indexPath.row]

return cell

override func viewDidLoad() {




Your allInformationByDate is a dictionary which contains the keys and values in unspecified order, and cannot be accessed with an integer subscript.

You should create an array which contains the dates in the desired order. In your case

let sortedDates = allInformationByDate.keys.sort()

would work. Then you can retrieve the data for an index path as

let date = sortedDates[indexPath.row]
let dayData = allInformationByDate[date]! // We _know_ that the dictionary value exists.