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

时间:2017-02-03 19:42:53

标签: 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
  }

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

  

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

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

  

[   “/e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg”   “/jjBgi2r5cRt36xF6iNUEhzscEcb.jpg”   “/tIKFBxBZhSXpIITiiB5Ws8VGXjt.jpg”]

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:11)

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

List<BigDecimal> items = Arrays.asList(BigDecimal.ONE, BigDecimal.valueOf(1.5), BigDecimal.valueOf(100));
items.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

答案 1 :(得分: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"]