swift can catch fatal error?

后端 未结 2 1622
执笔经年
执笔经年 2020-12-07 01:41

I am trying to use Swift 2.0 try-catch.

I originally had the following code

override func viewDidLoad()
{
    var obj : Object?;
    Hi( obj );
}
         


        
2条回答
  •  执笔经年
    2020-12-07 01:50

    When you're calling Hi() like this: open!.Hi();, your program can crash if open is nil.

    open is a parameter, and the value that is passed as that parameter is defined on the call site as such: var obj : Object?;. You're defining a new variable named obj with type Object?, but you're not assigning it a value. This means that obj will be nil and therefore open will be nil and this leads to open!.Hi() crashing.

    To solve it, make sure to assign a value to the parameter of Hi. It might be better to make the parameter non-optional as well, so you don't have to force unwrap it to call a function on it.

提交回复
热议问题