如何检查一个元素是否在数组中

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

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

问题描述

在 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() 是 协议扩展方法noreferrer">SequenceType(用于 Equatable 元素的序列)而不是全局方法,如早期版本.

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

备注:

  • 这个 contains() 方法要求序列元素采用 Equatable 协议,比较例如安德鲁斯的回答.
  • 如果序列元素是 NSObject 子类的实例那么你必须覆盖 isEqual:,参见 Swift 中的 NSObject 子类:hash vs hashValue,isEqual vs ==.
  • 还有另一种更通用的 contains() 方法,它不需要元素是相等的,而是将谓词作为论据,参见例如测试对象是否存在于Swift 的数组?.
  • 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")
}

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

本文标题为:如何检查一个元素是否在数组中

基础教程推荐