Abdullah Ajmal
Abdullah Ajmal

Reputation: 463

Problem with adding data to tableview in segmented control

I've got a segmented control that contains two items,

// Create a segmented control for the stories
let segmentedControl: UISegmentedControl = {
    let sc = UISegmentedControl(items: ["Participated Stories", "Drafts"])
    sc.addTarget(self, action: #selector(handleSegmentChange), for: .valueChanged)
    sc.selectedSegmentIndex = 0
    return sc
}()

// Create a list to store all the participated stories
let participatedStories = ["Hello", "Hey", "Hi"]
// Create a list to store all the drafts
let drafts = ["Sup", "Whatsup", "Gone"]
// Create a list to store the list that needs to be displayed
lazy var rowsToDisplay = participatedStories

@objc fileprivate func handleSegmentChange() {

    switch segmentedControl.selectedSegmentIndex {
    case 0:
        rowsToDisplay = participatedStories
    default:
        rowsToDisplay = drafts
    }
    tableView.reloadData()
}

What the handleSegmentChange function does is that it changes the data in the table view according to the tab that is selected in the segmented control. This is working properly. Now I want to retreive data from Firebase and display the data in the table view, here is what I tried:

// The data for the story Drafts
struct DraftStoriesData {

    var storyKey: String
    var storyTitle: String
    var votes: Int
}

// The data for the participated stories
struct ParticipatedStoriesData {

    var storyKey: String
    var storyTitle: String
    var votes: Int
}

let participatedStories: [ParticipatedStoriesData] = []
let drafts: [DraftStoriesData] = []
lazy var rowsToDisplay = participatedStories

@objc fileprivate func handleSegmentChange() {

    switch segmentedControl.selectedSegmentIndex {
    case 0:
        rowsToDisplay = participatedStories
    default:
        rowsToDisplay = drafts
    }
    tableView.reloadData()
}

But doing this gives an error -

Cannot assign value of type '[DraftStoriesData]' to type '[ParticipatedStoriesData]'

Upvotes: 0

Views: 52

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

Problem is here

rowsToDisplay = drafts

drafts is an array of type DraftStoriesData and rowsToDisplayis of type ParticipatedStoriesData so assignment won't compile as You repeat the same model

struct DraftStoriesData {

    var storyKey: String
    var storyTitle: String
    var votes: Int
}

// The data for the participated stories
struct ParticipatedStoriesData {

    var storyKey: String
    var storyTitle: String
    var votes: Int
}

you should delete 1 from above and use the other as the type of both arrays like

 var participatedStories: [ParticipatedStoriesData] = []
 var drafts: [ParticipatedStoriesData] = []

OR

 var participatedStories: [DraftStoriesData] = []
 var drafts: [DraftStoriesData] = []

Upvotes: 1

Related Questions