如何将自定义对象数组转换为字符串数组?

Swi*_*yJD 3 arrays swift

我目前有一组自定义对象

[GenrePosters]

其定义如下:

public struct GenrePosters: Decodable, Equatable{

  public let poster : String

  public init? (json: JSON) {

    guard let poster: String = "poster_path" <~~ json
      else {return nil}
    self.poster = poster
  }

  public static func ==(lhs: GenrePosters, rhs: GenrePosters) -> Bool {
    return lhs.poster == rhs.poster
  }
Run Code Online (Sandbox Code Playgroud)

打印到控制台时,它看起来像这样:

[MyMovieGuide.GenrePosters(海报:"/ e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg"),MyMovieGuide.GenrePosters(海报:"/ jjBgi2r5cRt36xF6iNUEhzscEcb.jpg"),MyMovieGuide.GenrePosters(海报:"/ tIKFBxBZhSXpIITiiB5Ws8VGXjt.jpg")]

我正在尝试将GenrePosters数组转换为只包含这样的海报值的字符串数组:

["/ e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg""/ jjBgi2r5cRt36xF6iNUEhzscEcb.jpg""/ tIKFBxBZhSXpIITiiB5Ws8VGXjt.jpg"]

任何帮助将不胜感激!

das*_*ght 11

您应该能够使用以下map(_:)方法执行此操作:

let posters = posterList.map {$0.poster}
Run Code Online (Sandbox Code Playgroud)