I'm trying to assign a value to x from a function f that takes one parameter (a string) and throws.
The current scope throws so I believe a do...catch isn't required.
I'm trying to use try with the coalescing operator ?? but I'm getting this error: 'try' cannot appear to the right of a non-assignment operator.
guard let x = try f("a") ??
try f("b") ??
try f("c") else {
print("Couldn't get a valid value for x")
return
}
If I change try to try?:
guard let x = try? f("a") ??
try? f("b") ??
try? f("c") else {
print("Couldn't get a valid value for x")
return
}
I get the warning Left side of nil coalescing operator '??' has non-optional type 'String??', so the right side is never used and the error: 'try?' cannot appear to the right of a non-assignment operator.
If I put each try? in brackets:
guard let x = (try? f("a")) ??
(try? f("b")) ??
(try? f("c")) else {
print("Couldn't get a valid value for x")
return
}
It compiles but x is an optional and I would like it to be unwrapped.
if I remove the questions marks:
guard let x = (try f("a")) ??
(try f("b")) ??
(try f("c")) else {
print("Couldn't get a valid value for x")
return
}
I get the error Operator can throw but expression is not marked with 'try'.
I'm using Swift 4.2 (latest in Xcode at time of writing).
What is the correct way to do this to get an unwrapped value in x?
Update:* f()'s return type is String?. I think the fact that it's an optional string is important.