iOS 结构编码和过滤器?

iOS Struct Codable and filter?

我想搜索特定的 U.S。 President by startYear,我试图在 Swift 4 中使用过滤器。我无法让它工作。我是故意使用 Codable 协议的。

struct USPresidents: Codable {
    let FName: String
    let LName: String
    let startYear: Int
    let endYear: Int
}

let widroww = USPresidents(FName: "Widrow", LName: "Wilson", startYear: 1913, endYear: 1921)
let fdr = USPresidents(FName: "Frankly", LName: "Roosevelt", startYear: 1933, endYear: 1945)
let jkf = USPresidents(FName: "John", LName: "Kennedy", startYear: 1961, endYear: 1963)
let dde = USPresidents(FName: "Dwight", LName: "Eisenhowser", startYear: 1953, endYear: 1961)
let anj = USPresidents(FName: "Andrew", LName: "Jackson", startYear: 1865, endYear: 1869)
let gew = USPresidents(FName: "George", LName: "Washington", startYear: 1789, endYear: 1796)

var allPresidents = [USPresidents]()
allPresidents.append(contentsOf: [fdr,jkf,dde,anj,gew])


let searchFor = [1953]
let result = allPresidents.filter {  [=11=].startYear.contains({ [=11=].searchFor.contains([=11=]) })
print("\n\nPresident in 1953 was:  = \(result)\n\n")

使用年份范围而不是单独的整数,然后您可以进行包含检查:

struct USPresident: Codable {
    let firstName: String
    let lastName: String
    let startYear: Int
    let endYear: Int

    var yearsInOffice: CountableClosedRange<Int> {
        return startYear...endYear
    }
}

let allPresidents = [
    USPresident(firstName: "Widrow",    lastName: "Wilson",         startYear: 1913, endYear: 1921),
    USPresident(firstName: "Frankly",   lastName: "Roosevelt",      startYear: 1933, endYear: 1945),
    USPresident(firstName: "John",      lastName: "Kennedy",        startYear: 1961, endYear: 1963),
    USPresident(firstName: "Dwight",    lastName: "Eisenhowser",    startYear: 1953, endYear: 1961),
    USPresident(firstName: "Andrew",    lastName: "Jackson",        startYear: 1865, endYear: 1869),
    USPresident(firstName: "George",    lastName: "Washington",     startYear: 1789, endYear: 1796),
]

let desiredYears = [1953]
let result = allPresidents.filter { president in
    desiredYears.contains(where:) { president.yearsInOffice.contains([=10=]) }
}
print("\n\nPresident in 1953 was:  = \(result)\n\n")

您希望过滤器查看 searchFor 是否包含 startYear

let result = allPresidents.filter { searchFor.contains([=10=].startYear) }

请注意,Codable 几乎不会为您的问题增加任何价值,因为您的查询在已经解码的对象上运行,并且 Codable 有助于从原始数据到结构实例的转换。

此外,将 searchFor 作为一个数组只会让事情变得复杂,如果您想知道谁是某年的总统。我建议回到简单的一年。

现在,进入正题,您可以使用 first(where:) 方法从列表中找出与给定查询匹配的第一个元素。

let searchFor = 1953
let result = allPresidents.first(where: { [=10=].startYear...[=10=].endYear ~= searchFor })
print("\n\n President in \(searchFor) was \(result)\n\n")

请注意,first(where:) returns 是可选的,因此如果要向前传递值,您可能需要解包该值。