Cartography icon indicating copy to clipboard operation
Cartography copied to clipboard

Binary operator '*' cannot be applied to two [Int] SWIFT

Open Mma2s opened this issue 9 years ago • 1 comments

Hi Guys,

I'm was just testing some code and i got the error in the description. Is er anyone that could help me with this??

var primeNumbers = [Int]()

let numbers = 2..<100

for n in numbers {

    //set the flag to true initially
    var prime = true


    for var i = 2; i <= n - 1; i += 1 {

        //even division of a number thats not 1 or the number itself, not a prime number
        if n % i == 0 {
            prime = false
            break
        }
    }

    if prime == false {

    }  else {

        primeNumbers.append(n)

    }


}

primeNumbers


var p = primeNumbers
var q = primeNumbers
var N = p * q // Here comes the failure.

Let me know guys!

Cheers!

Mma2s avatar Aug 11 '16 18:08 Mma2s

@Mma2s I'll assume you are a little lost and your questions is legit.

First of all, your question is a generic swift question that has nothing to do with this library in particular. You should post questions like that to stackoverflow.com.

Now, to your problem, you are getting that error because there is no operator defined for [Int] * [Int]. What would you expect as a result of that call? If what you expect is an array like:

N = [(p1*q1), (p2*q2), ..., (pn*qn)]

Then, you should implement the operator yourself or just run a loop. The operator would look like:

var p = primeNumbers
var q = primeNumbers

func *(lhs: [Int], rhs: [Int]) -> [Int] {
    assert(lhs.count == rhs.count, "Arrays must have the same length")
    var result = [Int](count: lhs.count, repeatedValue: 0)
    for i in 0..<lhs.count {
        result[i] = lhs[i] * rhs[i]
    }
    return result
}

var N = p * q

vfn avatar Aug 11 '16 23:08 vfn