Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping a throwing function in swift---double try

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?

like image 689
Paul Gowder Avatar asked Sep 15 '25 14:09

Paul Gowder


1 Answers

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")
}
like image 67
Rob Avatar answered Sep 17 '25 05:09

Rob