This question already has an answer here:
这个问题在这里已有答案:
- Shorthand to test if an object exists in an array for Swift? 2 answers
用于测试Swift数组中是否存在对象的简写? 2个答案
Is there any such statement to do something similar to below? or do I need to create a function?
是否有任何此类声明可以做类似下面的事情?还是我需要创建一个函数?
let x=[Double](1.023, 2.023, 3.023, 4.023, 5.023)
ler y=[Double](3.001)
if any of x > y{
("YES")}
2 个解决方案
#1
3
You can use the contains(where:)
method of Array.
您可以使用Array的contains(where :)方法。
let x = [1.023, 2.023, 3.023, 4.023, 5.023]
let y = 3.001
if x.contains(where: { $0 > y }) {
print("YES")
}
If you want to know the first value that was greater, you can do:
如果你想知道第一个更大的值,你可以这样做:
let x = [1.023, 2.023, 3.023, 4.023, 5.023]
let y = 3.001
if let firstLarger = x.first(where: { $0 > y }) {
print("Found \(firstLarger)")
}
If you want to know all that are larger, you can use filter
.
如果您想知道更大的所有内容,可以使用过滤器。
let x = [1.023, 2.023, 3.023, 4.023, 5.023]
let y = 3.001
let matches = x.filter { $0 > y }
print("The following are greater: \(matches)")
#2
0
let x = [1.023, 2.023, 3.023, 4.023, 5.023]
let y = [3.001]
let result = x.filter { $0 > y[0] }
print(result) // [3.023, 4.023, 5.023]
#1
3
You can use the contains(where:)
method of Array.
您可以使用Array的contains(where :)方法。
let x = [1.023, 2.023, 3.023, 4.023, 5.023]
let y = 3.001
if x.contains(where: { $0 > y }) {
print("YES")
}
If you want to know the first value that was greater, you can do:
如果你想知道第一个更大的值,你可以这样做:
let x = [1.023, 2.023, 3.023, 4.023, 5.023]
let y = 3.001
if let firstLarger = x.first(where: { $0 > y }) {
print("Found \(firstLarger)")
}
If you want to know all that are larger, you can use filter
.
如果您想知道更大的所有内容,可以使用过滤器。
let x = [1.023, 2.023, 3.023, 4.023, 5.023]
let y = 3.001
let matches = x.filter { $0 > y }
print("The following are greater: \(matches)")
#2
0
let x = [1.023, 2.023, 3.023, 4.023, 5.023]
let y = [3.001]
let result = x.filter { $0 > y[0] }
print(result) // [3.023, 4.023, 5.023]