I am attempting to use Swift Playground to use map(_:)
and enumerated()
to walk through an array of orders
, returning the first perfect match to a customers goods
.
However, when testing in Swift Playground; the map(_:)
function returns a string when it should be a tuple.
I'm attempting to retrieve the index and the value; of a given array filter.
Right now, my current solution is this;
let orders = [4,2,7]
let goods = 2
var matching:Int = (orders.filter{ $0 == goods }.first) ?? 0 as Int
In this example, the answer is 2
; however it doesn't give me the index of the array.
My second attempt in Swift Playground is thus
var r = (orders.filter{ $0 == goods }).enumerated().map { (index, element) -> (Int,Int) in
return (index, element)
}
print (r.first!) // This should report (0,2)
However, this in Swift Playground prints out in the sidebar panel
"(0, 2)\n"
Screenshot:
Why does the sidebar reporting that this is a string?
Is there a way to get the index and element correctly in this example?
Get Index of Orders that matches Goods
To get index & element:
or more compact:
Prints:
If you really want to find the first match only, a for loop is more efficient, as you can
break
after the first match is found.Playground
What you see
"(0, 2)\n"
is the result ofprint
. What it prints out in console is(0, 2)
plus newline.If you want to see the actual value of
r.first!
in the sidebar, remove the print:Result:
The print statement puts your output in
""
and also adds the linebreak\n
at the end.If you write
r.first!
, you will see that it actually is a tuple.Others have already covered the answer, this is just a side note. I suggest you break down your statement to make it clearer.