What is the difference when change to use optional chaining replace forced unwrapping in swift?

巧了我就是萌 提交于 2019-12-20 05:23:42

问题


When call a function of an object instance, the object may be not exist(optional type), it seems like you can always put an question mark behind the object name, instead of put an exclamation mark behind the object name, and not crash.

window!.rootViewController = containerViewController // forced unwrapping

// Can change to question mark and not crash. 
window?.rootViewController = containerViewController // Optional chaining

Is that in the place of use forced unwrapping, you can always change to use optional chaining, and the result is same? If yes, what is the difference?


回答1:


The difference is that by using ? you're stating you expect it to sometimes execute when window is nil and sometimes when it is not. In other words, having a nil window is a valid expectation.

ie, window? says that the window may or may not be nil. This means that .rootViewController = containerViewController may not execute because window is nil.

This will execute and not crash your app if window is nil.

Using ! however tells your application to always treat window as if it is not nil. If window is not nil, the statement will execute correctly, but if it is nil the app will crash because you're explicitly stating that you never EXPECT it to be nil.

To conclude, use:

window!.rootViewController = containerViewController

when you always expect the window to be valid in order to set your rootViewController

and use:

window?.rootViewController = containerViewController

when you are concerned about the state of window and whether or not a statement should execute based on that state.



来源:https://stackoverflow.com/questions/30323710/what-is-the-difference-when-change-to-use-optional-chaining-replace-forced-unwra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!