James Ryu James Ryu - 7 months ago 54
Swift Question

Efficient way to see if single array with certain set of value is present in 2d array containing several single array? Swift 4

Here is brief Swift 4 code:

let result = six49(draws: 1, lines: 5)

var collection = result.appendArrays()
var winningNumberToday: [Int] = result.winningNumber()


result
instance is initialized with
six49
class. It contains a function called
appendArrays()
, which generates certain lines of six sets of numbers (Five lines, in this case). Variable
collection
receives output of numbers in a type of
[[Int]]
. Output looks something like this:


[[1, 6, 19, 28, 29, 47], [5, 10, 13, 14, 18, 29], [5, 8, 16, 20, 35,
39], [6, 8, 11, 16, 42, 47], [3, 23, 26, 31, 34, 49]]


Another function of
result
instance produces one set of six numbers. It is stored in a variable called
winningNumberToday
(Type of
[Int]
). And the output looks like this:


[6, 10, 15, 30, 33, 45]


I want to write few lines of code that will efficiently determine whether
winningNumberToday
array (
[Int]
) values matches any of value in
collection
array
[[Int]]
.

I tried something like this, but it is not working:

collection.contains(where: winningNumberToday)


It would give me an error message like this:

error: MyPlayground.playground:82:28: error: cannot convert value of type '[Int]' to expected argument type '([Int]) throws -> Bool'
collection.contains(where: winningNumberToday)
^~~~~~~~~~~~~~~~~~

Answer Source

This should work:

if let ix = collection.index(where: {$0 == winningNumberToday}) {
    print("Index is \(ix)")
}
OR 
if collection.contains(where: {$0 == winningNumberToday}) {
    print("You won!")
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download