如何检查一个元素是否在数组中 [英] How to check if an element is in an array

查看:44
本文介绍了如何检查一个元素是否在数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Swift 中,如何检查一个元素是否存在于数组中?Xcode 没有关于 containincludehas 的任何建议,快速搜索这本书一无所获.知道如何检查吗?我知道有一个方法 find 可以返回索引号,但是有没有一个方法可以返回一个布尔值,如 ruby​​ 的 #include??

In Swift, how can I check if an element exists in an array? Xcode does not have any suggestions for contain, include, or has, and a quick search through the book turned up nothing. Any idea how to check for this? I know that there is a method find that returns the index number, but is there a method that returns a boolean like ruby's #include??

我需要的示例:

var elements = [1,2,3,4,5]
if elements.contains(5) {
  //do something
}

推荐答案

Swift 2, 3, 4, 5:

let elements = [1, 2, 3, 4, 5]
if elements.contains(5) {
    print("yes")
}

contains()SequenceType(用于 Equatable 元素的序列)而不是全局方法,如早期版本.

contains() is a protocol extension method of SequenceType (for sequences of Equatable elements) and not a global method as in earlier releases.

备注:

  • This contains() method requires that the sequence elements adopt the Equatable protocol, compare e.g. Andrews's answer.
  • If the sequence elements are instances of a NSObject subclass then you have to override isEqual:, see NSObject subclass in Swift: hash vs hashValue, isEqual vs ==.
  • There is another – more general – contains() method which does not require the elements to be equatable and takes a predicate as an argument, see e.g. Shorthand to test if an object exists in an array for Swift?.

Swift 旧版本:

let elements = [1,2,3,4,5]
if contains(elements, 5) {
    println("yes")
}

这篇关于如何检查一个元素是否在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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