问题描述
在 Swift 中,如何检查一个元素是否存在于数组中?Xcode 没有关于 contain
、include
或 has
的任何建议,快速搜索这本书一无所获.知道如何检查吗?我知道有一个方法 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 inearlier releases.
备注:
- 这个
contains()
方法要求序列元素采用Equatable
协议,比较例如安德鲁斯的回答. - 如果序列元素是
NSObject
子类的实例那么你必须覆盖isEqual:
,参见 Swift 中的 NSObject 子类:hash vs hashValue,isEqual vs ==. - 还有另一种更通用的
contains()
方法,它不需要元素是相等的,而是将谓词作为论据,参见例如测试对象是否存在于Swift 的数组?.
- This
contains()
method requires that the sequence elementsadopt theEquatable
protocol, compare e.g. Andrews's answer. - If the sequence elements are instances of a
NSObject
subclassthen you have to overrideisEqual:
, 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 anargument, 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")
}
这篇关于如何检查一个元素是否在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!