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.)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With