我想要做一个简单的任务来查找数组中是否存在(string)元素。 “contains”函数适用于一维数组,但不适用于二维数组。 有什么建议吗? (此功能的文档显得稀疏,或者我不知道去哪里找。)Swift 2使用包含多维数组的函数
1
A
回答
2
更新了斯威夫特3
的flatten
方法已更名为joined
现在。所以用法是
[[1, 2], [3, 4], [5, 6]].joined().contains(3) // true
对于多维数组,你可以使用flatten
降低一个维度。因此,对于二维数组:
[[1, 2], [3, 4], [5, 6]].flatten().contains(7) // false
[[1, 2], [3, 4], [5, 6]].flatten().contains(3) // true
0
不如J.Wangs回答,但另一种选择 - 你可以将列表减少使用减少一个布尔值(,结合:)功能。
[[1,2], [3,4], [5,6]].reduce(false, combine: {$0 || $1.contains(4)})
3
的夫特标准库不具有“多维数组”, 但是如果参考“嵌套的数组”(即一个阵列的阵列),那么 嵌套将工作,例如:
let array = [["a", "b"], ["c", "d"], ["e", "f"]]
let c = array.contains { $0.contains("d") }
print(c) // true
这里内方法是
public func contains(element: Self.Generator.Element) -> Bool
和外contains()
方法是谓词基于
public func contains(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool
其作为给定元素在内部阵列之一 发现尽快返回true
。
这种方法可以推广到更深的嵌套级别。
0
你也可以写一个扩展(SWIFT 3):
extension Sequence where Iterator.Element: Sequence {
func contains2D(where predicate: (Self.Iterator.Element.Iterator.Element) throws -> Bool) rethrows -> Bool {
return try contains(where: {
try $0.contains(where: predicate)
})
}
}
相关问题
- 1. PHP包含多维数组
- 2. 多维数组(2)
- 3. 对多维数组使用unshift函数
- 4. 多维数组的函数
- 5. 多维数组[String,UIImage](Swift)
- 6. Swift数组包含函数使构建时间长
- 7. 如何迭代包含数组对象的多维数组?
- 8. 多维数组foreach函数
- 9. 检查数组多维数组包含值或不
- 10. 使用多维数组引用函数的数组函数指针
- 11. 加入2多维数组
- 12. 创建包含数据库输出的多维数组
- 13. PHP:多维数组到函数调用
- 14. 使用单维数组中的数据创建多维数组
- 15. 2维数组
- 16. 2维数组
- 17. 在JS获取从多维数组Array包含价值指数
- 18. 函数返回0的多维数组
- 19. 在多维数组中的MATCH函数
- 20. 使用数组访问多维数组
- 21. Flex:包含组件的调用函数
- 22. 使用array_walk多维数组
- 23. actionscript:使用多维数组
- 24. 使用多维数组
- 25. SWIFT 2 - 按日期排序多维数组
- 26. 使用PHP的MySQL中的多维数组和聚合函数?
- 27. Matlab - 仅对多维数组的特定子维应用函数
- 28. 使用PHP array_multisort函数对多维关联数组进行排序,其中包含一些整数键
- 29. 2个多维数组的总和
- 30. Angular 2中的多维数组
谢谢! Swift文档确实涉及多维数组,但没有提供有关使用它们的很多信息。 – geoffry
这应该是一个被接受的答案。 – user1366265