如何从开关中获取多个值

How to get multiple values from a switch

我得到了 Int 数组,这是电影类型,我需要给每个元素相应的类型(例如:28 - “Action”,12 - “Adventure”)并将它们显示在 tableView 单元格中.

我只能显示一种流派,不能显示多种。你能帮我修复一个代码并给出一些关于如何正确获得流派的建议吗?

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!) 

据我了解,您希望从 genreIDs 数组中获取包含所有流派的字符串。

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

我认为采用枚举是一个很好的案例,您将拥有一个流派枚举

enum Genre: Int {
  case Action = 28
  case Adventure = 12
  case Animation = 16
  //.. list all your cases

  var name: String {
     "\(self)"
  }
}

那么在你的逻辑中你可以得到类似

的东西
let genres = genreIds.compactMap(Genre.init).map(\.name).joined(separator: ",")

干净且易于推理:)