7

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!

2

2 Answers 2

18

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

let posters = posterList.map {$0.poster}
Sign up to request clarification or add additional context in comments.

2 Comments

What about let posters = posterList.map{ $0.poster }? Is that different than gp in gp.poster?
Thanks, how to convert array of strings to array of objects?
0
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
    }
}

let genrePostersArray = [GenrePosters(poster: "one"), GenrePosters(poster: "two"), GenrePosters(poster: "three")]
let genrePostersStringArray = genrePostersArray.flatMap { $0.poster }
print(genrePostersStringArray) // ["one", "two", "three"]

1 Comment

Note that flatMap(_:) is unnecessary here as the result of the transform is non-optional – you can simply use map(_:) instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.