【问题标题】:Closure on collection that doesn't need to return anything [duplicate]关闭不需要返回任何东西的集合[重复]
【发布时间】:2017-05-26 08:43:54
【问题描述】:

我正在尝试编写一个函数来向NSAttributedString 添加属性。我已经将字典传递给函数...

 tag      attributes
[String : [String : Any]]

这些(标签和属性)然后将被传递给另一个函数以在给定标签内添加属性。

func addAttributes(attributes: [String: Any], forTag tag: String)

我能做到……

for (tag, attributes) in dictionary

但是有没有关闭的方法呢?

如果我使用平面地图...

dictionary.flatMap { addAtritbutes(attributes: $1, insideTag: $0) }

然后它抱怨我没有返回任何东西/使用调用的结果。是否有一个功能可以让我在没有警告的情况下执行此操作?

谢谢

【问题讨论】:

  • addAttributes()引入一个返回值。
  • 作为骗子关闭。找不到那个,谢谢@MartinR 我无法删除所以投票关闭。

标签: swift functional-programming closures


【解决方案1】:

您可以为此使用forEach 闭包。

dictionary.forEach {
    addAtritbutes(attributes: $0.value, insideTag: $0.key)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多