首页 > 解决方案 > 映射结构数组,将它们从一个 var 中过滤出来,然后提取该结构的另一个 var

问题描述

我有这两个结构:

struct AResult: Codable {
let section: String
let title: String
let abstract: String
let url: String
let byline: String
let updatedDate: String
let multimedia: [AMultimedia]

enum CodingKeys: String, CodingKey {
    case section, title, abstract, url, byline
    case updatedDate = "updated_date"
    case multimedia
}

// MARK: - AMultimedia
struct AMultimedia: Codable {
    let url: String
    let format: AFormat
}

enum AFormat: String, Codable {
    case mediumThreeByTwo210 = "mediumThreeByTwo210"
    case normal = "Normal"
    case standardThumbnail = "Standard Thumbnail"
    case superJumbo = "superJumbo"
    case thumbLarge = "thumbLarge"
}}

我需要的是:

在作为 AMultimedia 数组的多媒体中,获取格式为 thumbLarge 的元素,然后将相对 url 提取为字符串。

我尝试这样的事情:

$0.multimedia.filter { $0.format.rawValue.contains("Standard Thumbnail") }.map { $0.url }

但是 xcode 告诉我它是 [String] 而不是 String。

希望有人可以帮助我,非常感谢!

标签: arraysswiftfiltermapping

解决方案


要过滤并将结果连接到一个字符串,您可以这样做

$0.multimedia
    .filter { $0.format == .standardThumbnail }
    .map {$0.url}
    .joined(separator: ", ")

推荐阅读