Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2 Using "contains" function with multidimensional array

I am trying to do the simple task of finding if a (string) element exists in an array. The "contains" function works with a one-dimensional array, but not in a 2-dimensional array. Any suggestions? (Documentation on this function appears to be sparse, or I don't know where to look.)

like image 723
geoffry Avatar asked Apr 09 '26 03:04

geoffry


2 Answers

The Swift standard library does not have "multi-dimensional arrays", but if you refer to "nested arrays" (i.e. an array of arrays) then a nested contains() would work, for example:

let array = [["a", "b"], ["c", "d"], ["e", "f"]]
let c = array.contains { $0.contains("d") }
print(c) // true

Here the inner contains() method is

public func contains(element: Self.Generator.Element) -> Bool

and the outer contains() method is the predicate-based

public func contains(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool

which returns true as soon as the given element is found in one of the inner arrays.

This approach can be generalized to deeper nesting levels.

like image 144
Martin R Avatar answered Apr 11 '26 18:04

Martin R


Updated for Swift 3

The flatten method has been renamed to joined now. So the usage would be

[[1, 2], [3, 4], [5, 6]].joined().contains(3) // true

For multi-dimensional array, you can use flatten to decrease one dimension. So for two-dimensional array:

[[1, 2], [3, 4], [5, 6]].flatten().contains(7) // false

[[1, 2], [3, 4], [5, 6]].flatten().contains(3) // true
like image 27
J.Wang Avatar answered Apr 11 '26 20:04

J.Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!