A very small question. When I try to map a throwing function in Swift, the compiler makes me use the try keyword twice. For a toy example:
public func combineFiles(files: [String]) throws -> String {
let strings = try files.map { try String(contentsOfFile: $0) }
return strings.joined(separator: "\n\n")
}
Both of the try keywords in the second line seem to be necessary in order to get this to compile. But this just feels super-wrong to me---is there a way to do this kind of operation without a second try statement?
Technically, you could have a single try
if you avoid calling map
:
func combineFiles(files: [String]) throws -> String {
var results: [String] = []
for file in files {
results.append(try String(contentsOfFile: file))
}
return results.joined(separator: "\n\n")
}
But I think that’s going the wrong direction. I’d just embrace the two try
pattern that rethrowing functions like map
entail.
I’d lose strings
, though:
func combineFiles(files: [String]) throws -> String {
try files.map { try String(contentsOfFile: $0) }
.joined(separator: "\n\n")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With