用于测试对象是否存在于 Swift 数组中的简写? [英] Shorthand to test if an object exists in an array for Swift?
问题描述
目前,我有一个这样的对象数组:
Currently, I have an array of objects like this:
var myArr = [
MyObject(name: "Abc", description: "Lorem ipsum 1."),
MyObject(name: "Def", description: "Lorem ipsum 2."),
MyObject(name: "Xyz", description: "Lorem ipsum 3.")
]
在继续之前,我正在测试对象是否存在:
I am testing if an object exists before proceeding like this:
let item = myArr.filter { $0.name == "Def" }.first
if item != nil {
// Do something...
}
但我正在寻找一种更短的方法来做到这一点,因为我经常这样做.我想做这样的事情,但它是无效的:
But I'm looking for a shorter way to do this since I am doing this a lot. I'd like to do something like this but it is invalid:
if myArr.contains { $0.name == "Def" } {
// Do something...
}
是否有我遗漏的速记语法或更好的方法?
Is there any shorthand syntax I'm missing or a better way to do this?
推荐答案
为什么不使用内置的 contains()
函数?有两种口味
Why not use the built-in contains()
function? It comes in two flavors
func contains<S : SequenceType, L : BooleanType>(seq: S, predicate: @noescape (S.Generator.Element) -> L) -> Bool
func contains<S : SequenceType where S.Generator.Element : Equatable>(seq: S, x: S.Generator.Element) -> Bool
第一个将谓词作为参数.
and the first one takes a predicate as argument.
if contains(myArr, { $0.name == "Def" }) {
println("yes")
}
更新:从 Swift 2 开始,两个全局 contains()
函数都有被协议扩展方法取代:
Update: As of Swift 2, both global contains()
functions have
been replaced by protocol extension methods:
extension SequenceType where Generator.Element : Equatable {
func contains(element: Self.Generator.Element) -> Bool
}
extension SequenceType {
func contains(@noescape predicate: (Self.Generator.Element) -> Bool) -> Bool
}
第一个(基于谓词的)用作:
and the first (predicate-based) one is used as:
if myArr.contains( { $0.name == "Def" }) {
print("yes")
}
Swift 3:
if myArr.contains(where: { $0.name == "Def" }) {
print("yes")
}
这篇关于用于测试对象是否存在于 Swift 数组中的简写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!