swift - 在 Swift 中,如何使用匿名闭包参数显式指定 map 的返回值?

标签 swift dictionary return arguments

说我调用 map像这样,使用匿名闭包参数 $0 :

array.map {
  return $0.description
}

我将如何明确定义该 map 返回 string ?这不起作用:

array.map { -> String
  return $0.description
}

Contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored



这是否意味着如果我想指定一个返回值,我必须命名我的参数?

[编辑:我知道我在这里不需要明确的返回类型;仍然想如何指定一个]

最佳答案

您可以使用 as识别匿名外壳的类型。在这种情况下,您还需要指定输入的类型:

let result = array.map({ $0.description } as (CustomStringConvertible) -> String)

注:您可以使用 array 中的任何类型作为输入类型。这里我只使用了CustomStringConvertible协议(protocol),因为这是访问 .description 所需要的。属性(property)。

或者正如您所提到的,如果您为输入参数命名,则可以指定输出类型:
let result = array.map { value -> String in value.description }

另一种看待它的方式是注意 map返回 Array map 的任何类型关闭返回。您可以指定映射的结果是 [String]然后 Swift 会推断出 map关闭返回 String :
let result = array.map({ $0.description }) as [String]

或者
let result: [String] = array.map { $0.description }

关于swift - 在 Swift 中,如何使用匿名闭包参数显式指定 map 的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60304253/

相关文章:

ios - 除非我添加另一个 UIView,否则 ScrollView 中的 TableView 为空?

ios - 如何检测 30 秒持续时间

ios - 使用 Storyboard 时如何使用 Typhoon 导航到导航 Controller 中的 Controller

objective-c - 在 estimote ibeacon 上读取温度

c++ - 二叉堆与二叉树 C++

c# - CA2227 With Dictionary 解决方法是什么?

python - 当类中的函数返回一个值时,它返回到哪里?

python - 在python dict中访问多个值

javascript - ng-bind-html 返回单独的元素

C#生成一个在编译时返回类型未知的lambda表达式