Lawrence Gimenez

Collapsible List in SwiftUI

I wanted to share how I developed a comment thread using SwiftUI’s List, like in the video below.

The code is just very simple, we will leverage List’s children property. The code is very simple

List(topStory, children: \.chain) { story in
     StoryDetailsRowView(story: story)
}
.listStyle(.plain)

The main part is how we structure our data model. Take note of the chain variable.

import Foundation

class Story: Identifiable {

    let id = UUID()
    let user: User
    let title: String
    let content: String
    let date: String
    var chain: [Story]?
    
    init(user: User, title: String, content: String, date: String, chain: [Story]? = nil) {
        self.user = user
        self.title = title
        self.content = content
        self.date = date
        self.chain = chain
    }
    
    func setChain(_ chain: inout [Story]) {
        self.chain = chain
    }
}