线程1:致命错误:剩余或除以零

时间:2017-12-02 18:06:01

标签: swift fatal-error

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

  

线程1:致命错误:剩余或除以零)

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

这是我的代码:

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 !!!!!!!!!

我的代码中出现了什么问题?

1 个答案:

答案 0 :(得分:1)

如果长度为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.下面是一个使用turnery操作员的示例:

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