如何将一个定制对象数组转换为字符串数组?

时间:2021-07-28 17:42:27

I currently have an array of custom objects

我现在有一个自定义对象数组。

[GenrePosters]

(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")]

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

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

我尝试将genreposter的数组转换成字符串数组只有这样的海报值:

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

[" / e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg”“/ jjBgi2r5cRt36xF6iNUEhzscEcb.jpg”“/ tIKFBxBZhSXpIITiiB5Ws8VGXjt.jpg”)

Any help will be appreciated!

如有任何帮助,我们将不胜感激!

2 个解决方案

#1


5  

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

您应该能够使用map(_:)方法完成此操作:

let posters = posterList.map {$0.poster}

#2


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


5  

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

您应该能够使用map(_:)方法完成此操作:

let posters = posterList.map {$0.poster}

#2


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"]