我想通过startYear搜索特定的美国总统,我试图在Swift 4中使用过滤器。我无法让它工作。我故意使用Codable协议。
let x = {
test1: 4,
test2: 5,
'test3': 6
};
x.test1 // is 4
x.test2 // is 5
x.test3 // is 6
x['test1'] // is 4
x['test2'] // is 5
x['test3'] // is 6
const y = 'test1';
x.y // undefined. we never set a key of y.
x[y] // this is interpreted as x['test1'] so the result is 4
答案 0 :(得分:1)
使用年份范围而不是单独的Ints,然后您可以执行包含检查:
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($0) }
}
print("\n\nPresident in 1953 was: = \(result)\n\n")
答案 1 :(得分:1)
您希望过滤器查看searchFor
是否包含startYear
。
let result = allPresidents.filter { searchFor.contains($0.startYear) }
答案 2 :(得分:1)
请注意,Codable
几乎没有为您的问题增加任何值,因为您的查询在已经解码的对象上运行,Codable
有助于从原始数据到结构实例的转换。
此外,将searchFor
作为数组只会使某些事情变得复杂,如果你想知道在某一年中谁是总统。我建议回到简单的一年。
现在,进入追逐,您可以使用first(where:)
方法从列表中找出与给定查询匹配的第一个元素。
let searchFor = 1953
let result = allPresidents.first(where: { $0.startYear...$0.endYear ~= searchFor })
print("\n\n President in \(searchFor) was \(result)\n\n")
只需注意first(where:)
返回一个可选项,因此如果要将值向前传递,则可能需要解包该值。