3

A function which return Int? and throws error.

enum MyError : Error {
    case anError
}

func test(value:Int) throws -> Int? {
    guard value > 2 else {
        throw MyError.anError
    }
    return value
}

And I try it with if let like this.

if let val = try? test(value: 4) {
    print(val) // Optional(4)
}

val is optional inside if let brackets? why?

and this also gives optional value

if let val = try? test(value: 4) as Int? {
    print(val) // Optional(4)
}
Bilal
  • 18,478
  • 8
  • 57
  • 72
  • 3
    I don't know swift but isn't the result of the `try?` operator an optional expression containing the value of the expression (`test(value: 4)` in this case), which is then unwrapped into the `if` statement? Meaning you have optional of optional of int which gets unwrapped to optional of int? - https://stackoverflow.com/questions/24057171/what-the-meaning-of-question-mark-in-swift - since the method returns `Int?`, optional int, that's what you get inside the if-block. – Lasse V. Karlsen Nov 24 '17 at 07:46
  • change the return type to `Int` – Leo Dabus Nov 24 '17 at 07:47
  • 3
    Why is `test(value:)` declared to return an optional? It should either throw, or return a non-optional. – rmaddy Nov 24 '17 at 07:47
  • I don't know why @LeoDabus did close this question, I think it's a very good example. Anyhow, here's the answer: you have to remove the optional try: `if let val = try test(value: 4) { print(val) // 4 }` – cldrr Nov 24 '17 at 07:52
  • 2
    @cldrr: The question was *closed as a duplicate* because the same question has been asked and answered before. That does not say anything about the quality of this question. – Martin R Nov 24 '17 at 07:56
  • @cldrr BS is your comment Feel free to vote to reopen it. – Leo Dabus Nov 24 '17 at 07:57
  • 2
    No, that linked duplicate **precisely** matches this problem. It explains what the problem is, it explains how to handle it. – Lasse V. Karlsen Nov 24 '17 at 07:58
  • @cldrr Btw rmaddy suggested also to return a non-optional. What is it different from my comment "answer"? – Leo Dabus Nov 24 '17 at 08:02
  • @LeoDabus okay, BS is a bit harsh, sorry for that. But your both answers are not correct. Sometimes you don't have the option for changing the function definition. It's all about how to call such a function. Regarding the referred question: this question here is much better and brings it clearly to the point. – cldrr Nov 24 '17 at 10:02

0 Answers0