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.)
5 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.
1 Comment
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
Comments
let array = [["a", "b"], ["c", "d"], ["e", "f"]]
var c = array.contains { $0.contains("d") }
print(c) // true
c = array.contains{$0[1] == "d"}
print(c) // true
c = array.contains{$0[0] == "c"}
print (c) // true
if let indexOfC = array.firstIndex(where: {$0[1] == "d"}) {
print(array[indexOfC][0]) // c
print(array[indexOfC][1]) // d
} else {
print ("Sorry, letter is not in position [][letter]")
}
if let indexOfC = array.firstIndex(where: {$0[0] == "c"}) {
print(array[indexOfC][1]) // d
print(array[indexOfC][0]) // c
} else {
print ("Sorry, letter is not in position [letter][]")
}