在 Swift 中强制崩溃的最简单方法
Easiest way to force a crash in Swift
在 Swift 中强制崩溃的最简单方法是什么?
我只想使用一行代码(我可以快速添加的代码)。
我不想使用断点,我实际上希望应用程序崩溃。
[0][1]
这试图访问单元素数组的第二个元素。
通常你会使用
fatalError()
或
preconditionFailure()
为此。
它们的作用完全相同:终止程序,因此永远不会执行该语句之后的代码。所有具有此行为的函数都用 @noreturn
属性注释
您也可以这样做:
func getInt() -> Int {
fatalError()
}
该函数应该 return 一个 Int,但是因为程序永远不会到达那个点,所以您不必 return 任何东西。
您可以简单地尝试访问一个具有 nil 值的可选值...如果您已经声明了一个变量并且它是一个可选的,只需调用它(不要忘记解包)它会崩溃确定
如果你有一个整数变量,你可以将它乘以整数限制。 (UInt 的类似方法)
import Darwin
exit(0)
The C library function void exit(int status)
terminates the calling process immediately. Any open file descriptors belonging to the process are closed and any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal.
1/0
var a = 0
override func viewDidLoad() {
super.viewDidLoad()
_ = 1/a
反转范围,
21...3
Thread 1: Fatal error: Can't form Range with upperBound < lowerBound
在 Swift 中强制崩溃的最简单方法是什么?
我只想使用一行代码(我可以快速添加的代码)。
我不想使用断点,我实际上希望应用程序崩溃。
[0][1]
这试图访问单元素数组的第二个元素。
通常你会使用
fatalError()
或
preconditionFailure()
为此。
它们的作用完全相同:终止程序,因此永远不会执行该语句之后的代码。所有具有此行为的函数都用 @noreturn
属性注释
您也可以这样做:
func getInt() -> Int {
fatalError()
}
该函数应该 return 一个 Int,但是因为程序永远不会到达那个点,所以您不必 return 任何东西。
您可以简单地尝试访问一个具有 nil 值的可选值...如果您已经声明了一个变量并且它是一个可选的,只需调用它(不要忘记解包)它会崩溃确定
如果你有一个整数变量,你可以将它乘以整数限制。 (UInt 的类似方法)
import Darwin
exit(0)
The C library function
void exit(int status)
terminates the calling process immediately. Any open file descriptors belonging to the process are closed and any children of the process are inherited by process 1, init, and the process parent is sent a SIGCHLD signal.
1/0
var a = 0
override func viewDidLoad() {
super.viewDidLoad()
_ = 1/a
反转范围,
21...3
Thread 1: Fatal error: Can't form Range with upperBound < lowerBound