2

I am getting result as true for the following code

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

if elements1.contains (50) {

    print("true")

}

I am having problem finding out what the if condition should be for the following to get the result as true if elements2 has 50 in it.

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

3 Answers 3

6

You could use joined() to flatten the nested array in a single one, and apply the contains search on the joined array:

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

Note that you needn't include the type annotation for elements2 above, as the type is inferred (to [[Int]]).

Another alternative would be to use contains to check each inner array for the 50 element, and proceed if any of the inner arrays contains the value:

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

Or, using reduce to fold the inner arrays to a boolean, checking the possible inclusion of 50 in each inner array (quite similar approach to the one above)

if elements2.reduce(false, { $0 || $1.contains(50) }) {
    print("Contains 50!")
}
Sign up to request clarification or add additional context in comments.

2 Comments

Appreciate your explanation with alternatives
@Coder221 happy to help. Added also a reduce alternative, but I would personally probably prefer joined() (best semantics, imo).
5

I would probably use joined to simplify the task but you can easily use a nested contains:

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

if elements2.contains(where: { $0.contains(50) }) {
    print("true")
}

7 Comments

This has the advantage of "short-circuiting".
what is short-circuiting
@Coder221 It means that the search stops when the element is found. For example, the reduce solution has to iterate all the elements even if the first is the one you want to find.
Appreciate that, nice to know about it.
@dfri I think that joined would but I have doubts about map without explicitly using .lazy.
|
1

You can use flatMap for that.

let newArray = elements2.flatMap { $0 }
if newArray.contains(50) { 
    print("true") 
}

2 Comments

append{$1} also
newArray is executing 4 times (I have only 3 arrays in the array), even though I am getting desired result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.