在Swift中,如何使用匿名闭包参数显式指定map的返回值? [英] In Swift, how do I explicitly specify a return value for map with anonymous closure arguments?
问题描述
说我使用匿名闭包参数 $ 0
:
Say I call map
like this, using the anonymous closure argument $0
:
array.map {
return $0.description
}
我将如何明确定义该映射返回 string
?这不起作用:
How would I explicitly define that map returns a string
? This doesn’t work:
array.map { -> String
return $0.description
}
闭包参数列表的上下文类型需要1个参数,该参数不能隐式忽略
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?
推荐答案
您可以使用 as
来标识匿名附件的类型.在这种情况下,您还需要指定输入的类型:
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)
注意:您可以使用 array
中的任何类型作为输入类型.在这里,我只使用了 CustomStringConvertible
协议,因为这是访问 .description
属性所必需的.
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 }
查看它的另一种方法是注意 map
返回 map
闭包返回的任何类型的 Array
.您可以指定地图的结果为 [String]
,然后Swift会推断 map
闭包返回 String
:
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]
或
let result: [String] = array.map { $0.description }
这篇关于在Swift中,如何使用匿名闭包参数显式指定map的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!