BadmintonCat
BadmintonCat

Reputation: 9576

Swift Playground Error: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Getting the above error with the following code in 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)")
}

The error occurs on the line

var f:Bool = isPrime(i)

I already re-installed Xcode but error still appears. Does anyone know the reason behind this?

Upvotes: 0

Views: 1075

Answers (2)

R P
R P

Reputation: 1193

The reason you get "EXC_BAD_INSTRUCTION" is because the for loop's range operator cannot form a range with end value as 0. Your range operator's end value should be greater or equal to the start value.

From apple docs,

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.

This will work

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

but not this

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

Upvotes: 2

Mohammed Janish
Mohammed Janish

Reputation: 207

When the line var f:Bool = isPrime(i) is called, initial value of i is 0, division by zero gives an unknown value. Better change your loop to for i in 1 ..< 100

Upvotes: 0

Related Questions