Easiest way to force a crash in Swift

旧街凉风 提交于 2020-03-12 09:15:32

问题


What is the easiest way to force a crash in Swift?

I would like to use only one line of code (something that I can add quickly).

I don't want to use breakpoints, I actually want the app to crash.


回答1:


Typically you'd use

fatalError()

or

preconditionFailure()

for that.

These do exactly the same: terminating the program, therefore the code after this stamement never gets executed. All of the functions that have this behaviour are annotated with the @noreturn attribute

You can also do something like this:

func getInt() -> Int {
    fatalError()
}

The function is supposed to return an Int, but because the program never gets to that point, you don't have to return anything.




回答2:


[0][1]

This tries to access second element of a one element array.




回答3:


You can simply try to access an optional value that has nil value... if you already have a variable declared and it is an optional, just call it (don't forget to unwrap) and it will crash for sure




回答4:


If you have an integer variable, you can multiply it by the integer limit. (Similar method for UInt)



来源:https://stackoverflow.com/questions/32511178/easiest-way-to-force-a-crash-in-swift

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