Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Result initializer works in for loop but not map? #273

Open
getaaron opened this issue Oct 2, 2018 · 1 comment
Open

Result initializer works in for loop but not map? #273

getaaron opened this issue Oct 2, 2018 · 1 comment

Comments

@getaaron
Copy link

getaaron commented Oct 2, 2018

This code compiles without issue, where generatedEvents is of type [EKEvent] and eventStore is an EKEventStore:

for thisEvent in generatedEvents {
    let result = Result(try eventStore.save(thisEvent, span: .thisEvent, commit: false))
    print(result)
}

However, when I rewrite it as a map (to generate an array of Results):

let results = generatedEvents.map { thisEvent -> Result<(), AnyError> in
    let result = Result(try eventStore.save(thisEvent, span: .thisEvent, commit: false))
    print(result)
    return result
}

I receive the compiler error:

Call can throw, but it is not marked with 'try' and the error is not handled

However, looking at the Result initializer, it looks like the error is handled in a do/catch block.

@gstro
Copy link

gstro commented Oct 29, 2018

Not sure if you've moved past this, but it looks like something to do with the @autoclosure (could be a Swift bug?). One way to get this to work is to use curly braces instead of parentheses:

let result = Result { try eventStore.save(thisEvent, span: .thisEvent, commit: false) }

Here's an example I came up with to experiment:

extension String {
	func functionThatThrows() throws {
		_ = try String(contentsOf: URL(fileURLWithPath: NSTemporaryDirectory()))
	}
}

func example() {
	let strings = ["Hello,", "world!"]

	for string in strings {
		let result = Result(try string.functionThatThrows())  // works
		print(result)
	}

	let results = strings.map { string -> Result<(), AnyError> in
		let result = Result { try string.functionThatThrows() } // works 
//		let result = Result(try string.functionThatThrows())	// doesn't work
		print(result)
		return result
	}
	print(results)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants