gpt4 book ai didi

arrays - 如何找到数组数组中存在的整数?

转载 作者:搜寻专家 更新时间:2023-11-01 05:46:36 25 4
gpt4 key购买 nike

对于以下代码,我得到的结果为 true

var elements1:[Int] = [10, 20, 30, 40, 50]

if elements1.contains (50) {

print("true")

}

如果 elements2 在 50

var elements2:[[Int]] = [[10], [20, 30], [40, 50]]

最佳答案

您可以使用 joined() 将嵌套数组展平为单个数组,并对连接数组应用 contains 搜索:

let elements2 = [[10], [20, 30], [40, 50]]
if elements2.joined().contains(50) {
print("Contains 50!")
}

请注意,您不需要为上面的 elements2 添加类型注释,因为类型是推断出来的(到 [[Int]])。

另一种方法是使用 contains 检查每个内部数组中的 50 元素,如果任何内部数组包含该值则继续:

if elements2.map({ $0.contains(50) }).contains(true) {
print("Contains 50!")
}

或者,使用 reduce 将内部数组折叠为 bool 值,检查每个内部数组中是否可能包含 50(与上述方法非常相似)

if elements2.reduce(false, { $0 || $1.contains(50) }) {
print("Contains 50!")
}

关于arrays - 如何找到数组数组中存在的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41260922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com