【发布时间】:2020-03-28 05:57:58
【问题描述】:
我有这两个结构:
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。
希望有人能帮助我,非常感谢!
【问题讨论】:
-
错误必须与第一个 $0 有关,因为您的代码似乎工作正常。您应该使用枚举并将过滤器替换为
{ $0.format == .standardThumbnail } -
或者错误是指返回值是 [String] 而不是单个字符串
-
是的,问题是我需要一个单一的字符串。原因是我在需要字符串作为参数的结构的构造函数中执行所有这些操作
标签: arrays swift filter mapping