Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an array of custom objects to an array of strings?

Tags:

arrays

swift

I currently have an array of custom objects

[GenrePosters]

which is defined like so:

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
  }

When printed to console it looks like this:

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

I'm trying to convert the array of GenrePosters to an array of strings with only the poster values that like this:

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

Any help will be appreciated!

like image 224
SwiftyJD Avatar asked Dec 06 '22 15:12

SwiftyJD


1 Answers

You should be able to do this using map(_:) method:

let posters = posterList.map {$0.poster}
like image 193
Sergey Kalinichenko Avatar answered May 25 '23 11:05

Sergey Kalinichenko