在分段控件中向表视图添加数据的问题

Problem with adding data to tableview in segmented control

我有一个包含两个项目的分段控件,

// 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()
}

handleSegmentChange 函数的作用是根据在分段控件中选择的选项卡更改table 视图中的数据。这工作正常。现在我想从 Firebase 检索数据并在 table 视图中显示数据,这是我尝试过的:

// 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()
}

但是这样做会出错 -

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

问题出在这里

rowsToDisplay = drafts

draftsDraftStoriesData 类型的数组,rowsToDisplayParticipatedStoriesData 类型的数组,因此当您重复相同的模型时,赋值不会编译

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
}

你应该从上面删除 1 并使用另一个作为两个数组的类型,如

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

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