问题
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]
回答1:
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 }
回答2:
The type will be inferred automatically if it's a string , otherwise you need a cast like this
array.map { String($0.description) }
来源:https://stackoverflow.com/questions/60304253/in-swift-how-do-i-explicitly-specify-a-return-value-for-map-with-anonymous-clos