如何检查是否一个元素是一个数组 [英] How to check if an element is in an array
问题描述
在雨燕,我怎么能检查是否数组中存在的元素? X code没有对包含
,包含
或的<任何建议/ code>,并通过本书快速搜索却一无所获。任何想法如何检查呢?我知道,有一种方法
找到
返回索引号,但有一个返回boolean像Ruby的的#include <?/ $的方法C $ C>?
什么,我需要的例子:
VAR元素= [1,2,3,4,5]
如果elements.contains(5){
//做一点事
}
斯威夫特有一个内置的包含()
函数现在(X code 6测试6 ,可能已经在
previous beta版):
VAR元素= [1,2,3,4,5]
如果包含(元素,5){
的println(是)
}
更新:由于斯威夫特2, 包含()
不再是一个全球性的方法
但序列类型
的的协议扩展方法的(对于序列
的 Equatable
元素):
VAR元素= [1,2,3,4,5]
如果elements.contains(5){
打印(是)
}
说明:的
- 这
包含()
方法要求序列元件
采用Equatable
的协议,例如比较安德鲁斯的答案。 - 如果该序列的元素是
NSObject的
子类的实例
那么你必须重写的isEqual:
,见<一href=\"http://stackoverflow.com/questions/33319959/nsobject-subclass-in-swift-hash-vs-hashvalue-isequal-vs\">NSObject子类斯威夫特:哈希VS散列值,VS的isEqual == - 还有另一种 - 更通用 -
包含不需要的元素是equatable,并采取了predicate为()
方法
参数,例如见<一href=\"http://stackoverflow.com/questions/29679486/shorthand-to-test-if-an-object-exists-in-an-array-for-swift\">Shorthand测试是否在斯威夫特?数组存在的对象。
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?
?
Example of what I need:
var elements = [1,2,3,4,5]
if elements.contains(5) {
//do something
}
Swift has a built-in contains()
function now (Xcode 6 beta 6, probably already in
previous beta releases):
var elements = [1,2,3,4,5]
if contains(elements, 5) {
println("yes")
}
Update: As of Swift 2, contains()
is no longer a global method
but a protocol extension method of SequenceType
(for sequences
of Equatable
elements):
var elements = [1,2,3,4,5]
if elements.contains(5) {
print("yes")
}
Remarks:
- This
contains()
method requires that the sequence elements adopt theEquatable
protocol, compare e.g. Andrews's answer. - If the sequence elements are instances of a
NSObject
subclass then 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 an argument, see e.g. Shorthand to test if an object exists in an array for Swift?.
这篇关于如何检查是否一个元素是一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!