Thread 1: Fatal error: Remainder of or division by zero

Thread 1: Fatal error: Remainder of or division by zero

我有问题,当我 运行 我的项目崩溃时:

Thread 1: Fatal error: Remainder of or division by zero)

这是什么意思?解决方案是什么?

这是我的代码:

let answer: String = data.ans // This variable called from SQLite database
answer.replacingOccurrences(of: " ", with: "") // Delete spaces between words


let lenghtOfChar = answer as NSString
// char count
let width: Int = Int(view.frame.size.width) - 40
// frame width
var targetWidth: Int = (width - (lenghtOfChar.length - 1) * 5) / lenghtOfChar.length //Here's the crash !!!!!!!!!

我的代码有什么问题?

长度为0需要停止操作

let lenghtOfChar = (answer as NSString).length
guard lenghtOfChar != 0 else { return }
let width: Int = Int(view.frame.size.width) - 40
var targetWidth: Int = (width - (lenghtOfChar- 1) * 5)/lenghtOfChar

或者,您可以在长度为 0 时将宽度设置为 0。下面是一个使用车工操作员的示例:

let lenghtOfChar = answer as NSString
let width: Int = Int(view.frame.size.width) - 40
var targetWidth: Int = lenghtOfChar.length == 0 ? 0 : (width - (lenghtOfChar.length - 1) * 5)/lenghtOfChar.length