测试速记,如果在斯威夫特数组存在的对象? [英] Shorthand to test if an object exists in an array for Swift?

查看:114
本文介绍了测试速记,如果在斯威夫特数组存在的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有对象,像这样的数组:

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?

推荐答案

为什么不使用内置的包含()功能?它有两种形式

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

和第一个需要花费predicate作为参数。<​​/ P>

and the first one takes a predicate as argument.

if contains(myArr, { $0.name == "Def" }) {
    println("yes")
}

更新:由于斯威夫特2,包括全球包含()函数有
被取代的的协议扩展方法的:

extension SequenceType where Generator.Element : Equatable {
    func contains(element: Self.Generator.Element) -> Bool
}

extension SequenceType {
    func contains(@noescape predicate: (Self.Generator.Element) -> Bool) -> Bool
}

和所述第一(predicate为主)之一被用作

and the first (predicate-based) one is used as:

if myArr.contains( { $0.name == "Def" }) {
    print("yes")
}

这篇关于测试速记,如果在斯威夫特数组存在的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆