返回字符串而不是元组

返回字符串而不是元组

本文介绍了为什么 Swift Playground 中的 map(_:) 返回字符串而不是元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Swift Playground 来使用 map(_:)enumerated() 来遍历 orders 的数组,将第一个完美匹配返回给客户goods.

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.

但是,在 Swift Playground 中进行测试时;map(_:) 函数在应该是元组时返回一个字符串.

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

在这个例子中,答案是2;但是它没有给我数组的索引.

In this example, the answer is 2; however it doesn't give me the index of the array.

我在 Swift Playground 的第二次尝试是这样

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)

但是,这在 Swift Playground 中会在侧边栏面板中打印出来

However, this in Swift Playground prints out in the sidebar panel

"(0, 2)\n"

截图:

为什么侧边栏报告这是一个字符串?

Why does the sidebar reporting that this is a string?

有没有办法在这个例子中正确获取索引和元素?

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

推荐答案

获取与商品匹配的订单索引

获取索引 &元素:

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
}

或更紧凑:

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

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

打印:

r: (1, 2)

如果您真的只想找到第一个匹配项,for 循环更有效,因为您可以在找到第一个匹配项后break.

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.

游乐场

你看到的"(0, 2)\n"print的结果.它在控制台打印出来的是 (0, 2) 加上换行符.

What you see "(0, 2)\n" is the result of print. What it prints out in console is (0, 2) plus newline.

如果你想在侧边栏中看到 r.first! 的实际值,去掉打印:

If you want to see the actual value of r.first!in the sidebar, remove the print:

print (r.first!)
r.first!

结果:

这篇关于为什么 Swift Playground 中的 map(_:) 返回字符串而不是元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 08:33