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
Related Questions
- → How to write this recursive function in Swift?
- → Send email from a separated file using Swift Mailer
- → Laravel Mail Queue: change transport on fly
- → "TypeError: undefined is not an object" when calling JS function from Swift in tvOS app
- → Are Global/Nested functions in JavaScript implemented as closures?
- → JavascriptCore: executing a javascript-defined callback function from native code
- → Swift SHA1 function without HMAC
- → Shopify GraphQL using swift not getting response
- → How to disconnect git for a project in intellij?
- → Sending a request to a php web service from iOS
- → Add only objects that don't currently exist to Realm database
- → How to sort using Realm?
- → Realm object as member is nil after saving
Ad