개발/swift

Swift try catch error handling

lemonade 2020. 12. 1. 10:00
반응형

Error handling in swift

 

Try catch with throw makes error handling nicely in code.

 

let's talk about use cases and code example!

 

 

1. Method with throws

 

 

You can create method with throw easily.

 

Method with throw should call with try catch

otherwise you get "Call can throw but is not marked with try" error.

 

 

 

2. Struct initializer with throw

You can also use throw with struct init method.

 

This especially comes in handy when you want to validate properties for initializing a certain object.

 

 

 

 

You can create object like this. The catch block is only called when an error occurs.

 

Happy codding :)

반응형
그리드형

'개발 > swift' 카테고리의 다른 글

Swift How to ignore return value?  (0) 2020.12.08
Swift drag, drop and reorder collectionView Cell  (0) 2020.12.04
Swift new feature in ios14, IDFA  (0) 2020.11.26
Swift How to detect screenshot action?  (0) 2020.11.22
Swift What is Enumeration?  (0) 2020.11.20