Reputation: 185
I'm getting array of Int, which is film genres, and I need to give to each element corresponding genre (for example: 28 - "Action", 12 - "Adventure") and display them in tableView cell.
I could only display one genre, not multiple. Could you please help me fix a code and give some recommendations about how to properly get a genre.
func getGenre(filmGenres: [Int]) -> String {
var genre: String = "Action"
for i in filmGenres {
switch i {
case 28:
genre = "Action"
case 12:
genre = "Adventure"
case 16:
genre = "Animation"
case 35:
genre = "Comedy"
case 80:
genre = "Crime"
case 99:
genre = "Documentary"
case 18:
genre = "Drama"
case 10751:
genre = "Family"
case 14:
genre = "Fantasy"
case 36:
genre = "History"
case 27:
genre = "Horror"
case 10402:
genre = "Music"
case 9648:
genre = "Mystery"
case 10749:
genre = "Romance"
case 878:
genre = "Science Fiction"
case 10770:
genre = "TV Movie"
case 53:
genre = "Thriller"
case 10752:
genre = "War"
case 37:
genre = "Western"
default:
return ""
}
}
return genre
}
cell.filmGenre.text = movie.getGenre(filmGenres: movie.genreIDs!)
Upvotes: 0
Views: 47
Reputation: 816
I think it's a good case to embrace enums, you'll have an enum of Genre
enum Genre: Int {
case Action = 28
case Adventure = 12
case Animation = 16
//.. list all your cases
var name: String {
"\(self)"
}
}
Then in your logic you can have something that look like
let genres = genreIds.compactMap(Genre.init).map(\.name).joined(separator: ",")
clean and easy to reason about :)
Upvotes: 1
Reputation: 10199
As I understand, you want to get a string that contains all the genres from the genreIDs array.
let genreIds = [28, 12, 99, 12]
// Just to make sure we have unique genres.
// You may skip this if your application logic ensures this
let uniqGenreIds = Array(Set(genreIds))
// Create an sorted array with the textual genre names:
let stringGenres = uniqGenreIds.map {
(intGenre) -> String in
switch intGenre {
case 28:
return "Action"
case 12:
return "Adventure"
case 16:
return "Animation"
default: return "unknown"
}
}.sorted()
// Join the strings:
let allGenres = stringGenres.joined(separator: ",")
print (allGenres) // Action,Adventure,unknown
Upvotes: 1