Ad

How To Check For Multiple Cases Based On Label Name?

I have a view controller that contains a collection view on multiple categories. Different data and details including photos related to that category are fetched. I do not know how to make a case of switch statement regarding this. Writing the same code over and over does not seem like a good idea.

I have at least 14 different cells to cover...

Heres what I got

// Fetch posts based on trend name/hashtag
func fetchPosts() {
    if trendName == "Bike Shorts" {
        print("Fetching posts with the hashtag bikeshorts")
        HASHTAG_POST_REF.child("bikeshorts").observe(.childAdded) { (snapshot) in
            let postId = snapshot.key
            Database.fetchPost(with: postId, completion: { (post) in
                self.posts.append(post)
                self.collectionView?.reloadData()
            })
        }
    } else {
        if trendName == "Animal Prints" {
            self.trendDetails = "This is the label for animal prints"
            HASHTAG_POST_REF.child("animalprints").observe(.childAdded) { (snapshot) in
                let postId = snapshot.key
                Database.fetchPost(with: postId, completion: { (post) in
                    self.posts.append(post)
                    self.collectionView?.reloadData()
                })
            }
        }
    } else {
        if self.trendName == "Bermunda Shorts" {
            self.trendDetails = "This is the label for bermunda shorts"
            HASHTAG_POST_REF.child("bermundashorts").observe(.childAdded) { (snapshot) in
                let postId = snapshot.key
                Database.fetchPost(with: postId, completion: { (post) in
                    self.posts.append(post)
                    self.collectionView?.reloadData()
                })
            }
        }
    }
}
Ad

Answer

There is too much repetition here, I wouldn't use an if or a switch statement. The only things that change is the data.

Try something more dynamic...

struct Trend {
   let name: String
   let details: String
   let childValue: String
}

let trends = [
   Trend(name: "Bike Shorts", details: "Fetching posts with the hashtag bikeshorts", childValue: "bikeshorts"),
]

func fetchPosts() {
     let trend = trends.first { $0.name = trendName }

     self.trendDetails = trend.details
     HASHTAG_POST_REF.child(trend.childValue).observe(.childAdded) { (snapshot) in
         let postId = snapshot.key
         Database.fetchPost(with: postId, completion: { (post) in
             self.posts.append(post)
             self.collectionView?.reloadData()
         })
     }
}
Ad
source: stackoverflow.com
Ad