在Swift中,我如何检查数组中是否存在一个元素?Xcode并没有给出包含、包含或拥有的建议,快速搜索这本书也一无所获。知道怎么检查这个吗?我知道有一个方法找到返回索引号,但是否有一个方法返回一个布尔像ruby的#include??
我需要的例子:
var elements = [1,2,3,4,5]
if elements.contains(5) {
//do something
}
在Swift中,我如何检查数组中是否存在一个元素?Xcode并没有给出包含、包含或拥有的建议,快速搜索这本书也一无所获。知道怎么检查这个吗?我知道有一个方法找到返回索引号,但是否有一个方法返回一个布尔像ruby的#include??
我需要的例子:
var elements = [1,2,3,4,5]
if elements.contains(5) {
//do something
}
当前回答
如果用户发现特定的数组元素,则使用以下代码相同的整数值。
var arrelemnts = ["sachin", "test", "test1", "test3"]
if arrelemnts.contains("test"){
print("found") }else{
print("not found") }
其他回答
数组
let elements = [1, 2, 3, 4, 5, 5]
检查元素是否存在
elements.contains(5) // true
获取元素索引
elements.firstIndex(of: 5) // 4
elements.firstIndex(of: 10) // nil
获取元素计数
let results = elements.filter { element in element == 5 }
results.count // 2
斯威夫特
如果你不使用object,那么你可以使用此代码用于contains。
let elements = [ 10, 20, 30, 40, 50]
if elements.contains(50) {
print("true")
}
如果你在swift中使用NSObject类。这个变量符合我的要求。您可以根据自己的需求进行修改。
var cliectScreenList = [ATModelLeadInfo]()
var cliectScreenSelectedObject: ATModelLeadInfo!
这是针对相同的数据类型。
{ $0.user_id == cliectScreenSelectedObject.user_id }
如果你想要AnyObject类型。
{ "\($0.user_id)" == "\(cliectScreenSelectedObject.user_id)" }
已满的状况
if cliectScreenSelected.contains( { $0.user_id == cliectScreenSelectedObject.user_id } ) == false {
cliectScreenSelected.append(cliectScreenSelectedObject)
print("Object Added")
} else {
print("Object already exists")
}
为Swift 2+更新
请注意,从Swift 3(甚至2)开始,下面的扩展不再需要,因为全局contains函数已经被做成了Array上的一对扩展方法,这允许你做以下任何一种:
let a = [ 1, 2, 3, 4 ]
a.contains(2) // => true, only usable if Element : Equatable
a.contains { $0 < 1 } // => false
Swift 1的历史答案:
使用这个扩展:(更新到Swift 5.2)
extension Array {
func contains<T>(obj: T) -> Bool where T: Equatable {
return !self.filter({$0 as? T == obj}).isEmpty
}
}
使用:
array.contains(1)
像这样使用哈希表如何?
首先,创建一个“哈希映射”泛型函数,扩展Sequence协议。
extension Sequence where Element: Hashable {
func hashMap() -> [Element: Int] {
var dict: [Element: Int] = [:]
for (i, value) in self.enumerated() {
dict[value] = i
}
return dict
}
}
这个扩展将工作,只要数组中的项目符合Hashable,像整数或字符串,这里是用法…
let numbers = Array(0...50)
let hashMappedNumbers = numbers.hashMap()
let numToDetect = 35
let indexOfnumToDetect = hashMappedNumbers[numToDetect] // returns the index of the item and if all the elements in the array are different, it will work to get the index of the object!
print(indexOfnumToDetect) // prints 35
但现在,我们只检查元素是否在数组中。
let numExists = indexOfnumToDetect != nil // if the key does not exist
means the number is not contained in the collection.
print(numExists) // prints true
(3)迅速
检查数组中是否存在元素(满足某些条件),如果存在,则继续处理第一个这样的元素
如果意图是:
要检查数组中是否存在一个元素(/满足一些布尔标准,不一定是相等性测试), 如果是,继续处理第一个这样的元素,
然后包含(_:)作为蓝图序列的替代是序列的第一个(where:):
let elements = [1, 2, 3, 4, 5]
if let firstSuchElement = elements.first(where: { $0 == 4 }) {
print(firstSuchElement) // 4
// ...
}
在这个虚构的例子中,它的使用可能看起来很愚蠢,但是如果查询非基本元素类型的数组中是否存在满足某些条件的元素,它是非常有用的。如。
struct Person {
let age: Int
let name: String
init(_ age: Int, _ name: String) {
self.age = age
self.name = name
}
}
let persons = [Person(17, "Fred"), Person(16, "Susan"),
Person(19, "Hannah"), Person(18, "Sarah"),
Person(23, "Sam"), Person(18, "Jane")]
if let eligableDriver = persons.first(where: { $0.age >= 18 }) {
print("\(eligableDriver.name) can possibly drive the rental car in Sweden.")
// ...
} // Hannah can possibly drive the rental car in Sweden.
let daniel = Person(18, "Daniel")
if let sameAgeAsDaniel = persons.first(where: { $0.age == daniel.age }) {
print("\(sameAgeAsDaniel.name) is the same age as \(daniel.name).")
// ...
} // Sarah is the same age as Daniel.
使用.filter{…某些条件。First可以替换为First(其中:)。后者更好地显示了意图,并且比.filter可能的非惰性工具具有性能优势,因为这些工具将在提取(可能的)第一个通过过滤器的元素之前传递整个数组。
检查数组中是否存在元素(满足某些条件),如果存在,则删除第一个这样的元素
下面的评论质疑道:
如何从数组中删除firstSuchElement ?
与上面类似的用例是删除满足给定谓词的第一个元素。为此,可以使用Collection的index(where:)方法来查找实现谓词的第一个元素的索引,然后使用array To的remove(at:)方法(可能;如果它存在)删除该元素。
var elements = ["a", "b", "c", "d", "e", "a", "b", "c"]
if let indexOfFirstSuchElement = elements.index(where: { $0 == "c" }) {
elements.remove(at: indexOfFirstSuchElement)
print(elements) // ["a", "b", "d", "e", "a", "b", "c"]
}
或者,如果你想从数组中删除元素并使用它,应用Optional:s map(_:)方法有条件地(for .some(…)return from index(where:))使用result from index(where:)从数组中删除并捕获被删除的元素(在可选的绑定子句中)。
var elements = ["a", "b", "c", "d", "e", "a", "b", "c"]
if let firstSuchElement = elements.index(where: { $0 == "c" })
.map({ elements.remove(at: $0) }) {
// if we enter here, the first such element have now been
// remove from the array
print(elements) // ["a", "b", "d", "e", "a", "b", "c"]
// and we may work with it
print(firstSuchElement) // c
}
注意,在上面虚构的例子中,数组成员是简单的值类型(String实例),因此使用谓词来查找给定的成员有点过分,因为我们可以简单地使用@DogCoffee的回答中所示的更简单的index(of:)方法来测试是否相等。但是,如果将上面的查找-删除方法应用于Person示例,则使用index(where:)和谓词是合适的(因为我们不再测试是否相等,而是测试是否满足提供的谓词)。