是否有类似于Swift 3.0 Xcode中的“If Any”的声明[重复]

时间:2023-02-09 10:02:49

This question already has an answer here:

这个问题在这里已有答案:

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]