Why does map(_:) in Swift Playground return a Stri

2019-06-28 03:28发布

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:

swift playground

Why does the sidebar reporting that this is a string?

Is there a way to get the index and element correctly in this example?

标签: swift swift3
3条回答
聊天终结者
2楼-- · 2019-06-28 03:48

Get Index of Orders that matches Goods

To get index & element:

var r = orders.enumerated().map { ( index, element) -> (Int, Int) in
    return (index, element)
}.filter { (index, element) -> Bool in
    if element == goods {
        return true
    }
    return false
}

or more compact:

var r = orders.enumerated().map { index, element in (index, element) }
    .filter { _, element in element == goods ? true : false }

print("r: \(r.first)")

Prints:

r: (1, 2)

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 of print. 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:

print (r.first!)
r.first!

Result:

查看更多
放荡不羁爱自由
3楼-- · 2019-06-28 03:53

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.

查看更多
趁早两清
4楼-- · 2019-06-28 03:54

Others have already covered the answer, this is just a side note. I suggest you break down your statement to make it clearer.

var r = orders.filter{ $0 == goods }
              .enumerated()
              .map{ index, element in (index, element) }
查看更多
登录 后发表回答