WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Recreating a Social Media Feed

Forums > SwiftUI

So basically i was trying to understand how to recreate a social media feed. While i was working with Image objects it was simple I had one image array and i just used a foreach loop for the feed.

array = [ImagePost]()

ForEach(vm.array) { post in

   NewImagePost(post: post)

}

So now I have three arrays

let array1 = [ImagePost]()
let array2 = [VideoPost]()
let array3 = [TweetPost]()

And now how do i incorporate three different objects? I have different objects for NewVideo and Newtweets. How can i use a foreach loop to create a Chronological feed. (I have a different NewImagePost, NewVideoPost, NewTweetPost and I dont want to incorporate all of them into one object with an enum) What are some other solutions? Thank you very much.

   

You could try make a protocol

protocol Post {
    var id: UUID { get }
    var date: Date { get set }
    var description: String { get set }
}

Then you structs have this protocol

struct ImagePost: Post {
    let id = UUID()
    var date: Date
    var description: String
}

struct VideoPost: Post {
    let id = UUID()
    var date: Date
    var description: String
}

struct TweetPost: Post {
    let id = UUID()
    var date: Date
    var description: String
}

Then the arrays of each type (note that i used Date.now for each date just for demo)

let imagePosts = [
    ImagePost(date: Date.now, description: "ImagePost1"),
    ImagePost(date: Date.now, description: "ImagePost2")
]

let videoPosts = [
    VideoPost(date: Date.now, description: "VideoPost1"),
    VideoPost(date: Date.now, description: "VideoPost2")
]

let tweetPosts = [
    TweetPost(date: Date.now, description: "TweetPost1"),
    TweetPost(date: Date.now, description: "TweetPost2")
]

Now you can combine them

var combinePosts: [Post] {
    imagePosts + videoPosts + tweetPosts
}

Now you can use in List or ForEach

var body: some View {
    List(combinePosts, id: \.id) { post in
        Text(post.description)
    }
}

PS once you have the combinePost you can then sort it by date.

   

Save 50% in my Black Friday sale.

SAVE 50% To celebrate WWDC22, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.