How to check if an element is in an array(如何检查一个元素是否在数组中)
问题描述
在 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 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 theEquatableprotocol, compare e.g. Andrews's answer. - If the sequence elements are instances of a
NSObjectsubclass 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?.
Swift 旧版本:
let elements = [1,2,3,4,5]
if contains(elements, 5) {
println("yes")
}
这篇关于如何检查一个元素是否在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检查一个元素是否在数组中
基础教程推荐
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
