【问题标题】:Why does map(_:) in Swift Playground return a String and not a tuple?为什么 Swift Playground 中的 map(_:) 返回一个字符串而不是一个元组?
【发布时间】:2016-12-14 02:53:16
【问题描述】:

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

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

我正在尝试检索索引和值;给定数组过滤器。

目前,我目前的解决方案是这样的;

let orders = [4,2,7]
let goods = 2
var matching:Int = (orders.filter{ $0 == goods }.first) ?? 0 as Int

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

因此,我在 Swift Playground 中的第二次尝试是

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 中的 this 在侧边栏面板中打印出来

"(0, 2)\n"

截图:

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

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

【问题讨论】:

标签: swift swift3


【解决方案1】:

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

获取索引和元素:

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


游乐场

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

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

print (r.first!)
r.first!

结果:

【讨论】:

  • for循环真的更高效吗?我认为过滤器是从旧目标 c 复制子查询想法的好方法。但如果是这样的话;也许我会用那个。
  • 在您只想要第一个匹配的特定情况下效率更高,因为您可以break for 循环,因此其他orders 不会被处理。
  • 明白。感谢您在这方面的帮助。我想将来我会使用 for 循环;我想使用过滤器,因为我认为解决方案有理由(a)使用过滤器和(b)我以前从未做过过滤器。无论如何,谢谢。
【解决方案2】:

其他人已经涵盖了答案,这只是一个旁注。我建议你分解你的陈述以使其更清楚。

var r = orders.filter{ $0 == goods }
              .enumerated()
              .map{ index, element in (index, element) }

【讨论】:

  • 从现在开始我会这样做。谢谢
【解决方案3】:

打印语句将您的输出放在"" 中,并在末尾添加换行符\n

如果你写r.first!,你会发现它实际上是一个元组。

【讨论】:

  • 是的,这只是我的困惑。我提前道歉。
猜你喜欢
  • 2020-03-10
  • 1970-01-01
  • 2017-09-19
  • 2020-04-08
  • 1970-01-01
  • 2020-07-04
  • 1970-01-01
  • 2016-06-15
  • 1970-01-01
相关资源
最近更新 更多