Search code examples
swiftfatal-error

Why do I get the EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) in swift


I am only two weeks into swift so my code will be very basic and not perfect I am trying to solve this problem "Create a function that returns the minimum number of removals to make the sum of all elements in an array even." like this minimumRemovals([1, 2, 3, 4, 5]) ➞ 1

minimumRemovals([5, 7, 9, 11]) ➞ 0

minimumRemovals([5, 7, 9, 12]) ➞ 1

but I keep get the error EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

Here is my code

'''

func minimumRemovals( arr: [Int]) -> Int {
    var odds = 0
    var evens = 0
    for i in arr {
        if arr[i] % 2 == 0 {
            evens += 1
        } else {
            odds += 1
        }
    }
    if odds == evens {
        return 1
    } else {
        return 0
    }
}
print(minimumRemovals(arr: [1,2,3,4,5]))
'''

Solution

  • for .. in .. in Swift does not iterate over indices. It iterates over actual array elements. Hence i is the element, not the index.

    Using if i % 2 == 0 will fix your problem.