I have a horizontal scrolling UICollectionView with each collectionViewCell containing a tableView displaying a feed of post objects. I would like to fetch data only once for each collectionViewCell.

My current implementation fetches data whenever the collectionViewCell is being dequeued, ie when the user swipes left and right on the collectionView, the cell sometimes reloads and fetches data, interrupting the user experience.


//At ViewController
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! FeedCell
    cell.topic = topics[indexPath.item]
    return cell

//At FeedCell, the custom collectionViewCell
class FeedCell: UICollectionViewCell {

    lazy var tableView: UITableView = {
        let tv = UITableView(frame: .zero, style: .plain)
        //Setup tableView work
        return tv

    var topic: Topic? {
        didSet {
             if let _ = topic {

    override init(frame: CGRect) {
        super.init(frame: frame)
        //Setup views work


Attempt 1, move getData() to init(frame: CGRect), but getData doesn't get called as topic isn't set yet.

Attempt 2, move getData() to layoutSubviews() like so:

override func layoutSubviews() {
    if let _ = topic {



But this recursively calls getData().