目前,我有一个这样的对象数组:
var myArr = [ MyObject(name: "Abc", description: "Lorem ipsum 1."), MyObject(name: "Def", description: "Lorem ipsum 2."), MyObject(name: "Xyz", description: "Lorem ipsum 3.") ]
我正在测试是否存在对象,然后再进行如下操作:
let item = myArr.filter { $0.name == "Def" }.first if item != nil { // Do something... }
但是我正在寻找一种更短的方法来执行此操作,因为我经常这样做。我想做这样的事情,但这是无效的:
if myArr.contains { $0.name == "Def" } { // Do something... }
是否有我缺少的速记语法或更好的方法?
为什么不使用内置contains()功能?它有两种口味
contains()
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
第一个以谓词为参数。
if contains(myArr, { $0.name == "Def" }) { println("yes") }
更新:从Swift 2开始, 两个全局contains()函数都已被 协议扩展方法 取代:
extension SequenceType where Generator.Element : Equatable { func contains(element: Self.Generator.Element) -> Bool } extension SequenceType { func contains(@noescape predicate: (Self.Generator.Element) -> Bool) -> Bool }
第一个(基于谓词的)用作:
if myArr.contains( { $0.name == "Def" }) { print("yes") }
斯威夫特3:
if myArr.contains(where: { $0.name == "Def" }) { print("yes") }