Optionals vs Throwing functions

前端 未结 3 583
星月不相逢
星月不相逢 2021-02-04 01:56

Consider the following lookup function that I wrote, which is using optionals and optional binding, reports a message if key is not found in the dictionary

func          


        
3条回答
  •  庸人自扰
    2021-02-04 02:27

    If you are using Swift 2.0 you could use both versions. The second version uses try/catch (introduced with 2.0) and is thus not backwards compatible which might be a disadvantage to consider.

    If there is any performance difference then it will be neglectable.

    My personal favorite is the first one as it is straight forward and well readable. If I had to do maintenance of the second version I would ask myself why the author took a try/catch approach for such a simple case. So I would rather be confused...

    If you had many complex conditions with many exit points (throws) then I would go for the second one. But as I said, this is not the case here.

提交回复
热议问题