在 Swift 中,如何使用匿名闭包参数显式指定 map 的返回值? [英] In Swift, how do I explicitly specify a return value for map with anonymous closure arguments?
问题描述
假设我像这样调用 map
,使用匿名闭包参数 $0
:
array.map {返回 $0.description}
我将如何明确定义该映射返回一个 string
?这不起作用:
array.map { ->细绳返回 $0.description}
<块引用>
闭包参数列表的上下文类型需要 1 个参数,不能隐式忽略
这是否意味着如果我想指定一个返回值,我必须为我的参数命名?
您可以使用 as
来标识匿名围栏的类型.在这种情况下,您还需要指定输入的类型:
let result = array.map({ $0.description } as (CustomStringConvertible) -> String)
注意:您可以使用 array
中的任何类型作为输入类型.这里我只使用了 CustomStringConvertible
协议,因为这是访问 .description
属性所需要的.
或者如您所提到的,如果您为输入参数命名,则可以指定输出类型:
let result = array.map { value ->value.description 中的字符串 }
<小时>
另一种看待它的方式是注意 map
返回一个 Array
任何类型的 map
闭包返回.你可以指定 map 的结果是 [String]
,然后 Swift 会推断 map
闭包返回 String
:
let result = array.map({ $0.description }) as [String]
或
let 结果:[String] = array.map { $0.description }
Say I call map
like this, using the anonymous closure argument $0
:
array.map {
return $0.description
}
How would I explicitly define that map returns a string
? This doesn’t work:
array.map { -> String
return $0.description
}
Contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored
Does that mean if I want to specify a return value I have to name my arguments?
[EDIT: I know I do not need an explicit return type here; still would like how to specify one]
You can use as
to identify the type of the anonymous enclosure. In this case you'll need to specify the type of the input as well:
let result = array.map({ $0.description } as (CustomStringConvertible) -> String)
Note: You could use the type of whatever is in array
as the input type. Here I just used the CustomStringConvertible
protocol since that is what is needed to be able to access the .description
property.
or as you mentioned, you can specify the output type if you give a name to the input parameter:
let result = array.map { value -> String in value.description }
Another way to look at it is to note that map
returns an Array
of whatever type the map
closure returns. You could specify that the result of the map is [String]
and Swift would then infer that the map
closure returns String
:
let result = array.map({ $0.description }) as [String]
or
let result: [String] = array.map { $0.description }
这篇关于在 Swift 中,如何使用匿名闭包参数显式指定 map 的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!