create a sum function that has a bug in it in swift

Here's an example of a sum function in Swift that has a bug:

main.swift
func sum(numbers: [Int]) -> Int {
    var result = 0
    for number in numbers {
        result += number
    }
    return result + 1 // introducing bug here by adding 1 to result
}

let numbers = [1, 2, 3, 4, 5]
let total = sum(numbers: numbers)
print(total) // Output: 16, which is incorrect due to the introduced bug
320 chars
12 lines

In this example, the sum function takes an array of Int values and returns the sum of those values. However, there is a bug in the implementation, where the result variable gets modified by adding 1 to it, resulting in a wrong total. The code compiles without errors, so it is not immediately clear that there is a bug in the function. The bug can be fixed by simply removing the + 1 on the return statement.

related categories

gistlibby LogSnag