UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

1      

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.

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.