xcode - swift Playground 错误 : EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, 子代码 = 0x0)

标签 xcode swift

在 Playground Xcode 7.1.1 中使用以下代码出现上述错误:

import Cocoa

func countDivisors(number:Int) -> Int
{
    var c = 0
    for i in 1 ... number
    {
        if number % i == 0 { ++c }
    }
    return c
}

func isPrime(number:Int) -> Bool
{
    return countDivisors(number) == 2
}

isPrime(2);

for i in 0 ..< 100
{
    var f:Bool = isPrime(i)
    print("\(i): \(f)")
}

错误发生在线路上

var f:Bool = isPrime(i)

我已经重新安装了 Xcode,但错误仍然出现。有谁知道这背后的原因吗?

最佳答案

你得到“EXC_BAD_INSTRUCTION”的原因是因为 for 循环的范围运算符不能形成一个结束值为 0 的范围。你的范围运算符的结束值应该大于或等于起始值。

来自苹果文档,

The closed range operator (a...b) defines a range that runs from a to b, and includes the values a and b. The value of a must not be greater than b.

这会起作用

for i in 1...1 {
   //--  
}

但不是这个

for i in 1...0 {
  //--  
}

关于xcode - swift Playground 错误 : EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, 子代码 = 0x0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33967693/

相关文章:

ios - 将 PFObject 附加到数组 - EXC_BAD_ACCESS

ios - 为什么我不必在 Swift 中使用 NSBundle 之前导入 Foundation?

iphone - UIScrollView 只随文本滚动

database - Swift - Firebase 多个快照

ios - 自定义tableview滚动效果,如google底漆

ios - 如何在appdelegate中调用viewController的方法

ios - 在 Swift 中将子层调整为 UIView 边界

ios - 当我验证应用程序时,Xcode 管理器无法列出我的所有应用程序

xcode - 如何创建外观和工作方式与Apple Core Library中的外观类似的Xcode文档集

ios - 如何覆盖约束