当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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!

网友答案:

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

let posters = posterList.map {$0.poster}
网友答案:
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"]
分享给朋友:
您可能感兴趣的文章:
随机阅读: