1

I want to compare if 2 arrays are equal, here is my code:

  var letteronloc = [String]();
      letteronloc.append("test")
  let characters = Array("test")


   if(letteronloc == characters) {

    }

but i have an error: could not find an overload for == that accepts the supplied arguments

I think its because the arrays are not equal, because the second array is not an string array. But how can i fix this?

JWWalker
  • 22,385
  • 6
  • 55
  • 76
da1lbi3
  • 4,369
  • 6
  • 31
  • 65
  • possible duplicate of [Compare arrays in swift](http://stackoverflow.com/questions/27567736/compare-arrays-in-swift) – Icaro Jun 03 '15 at 20:00
  • 1
    @IcaroNZ no it's not, because i know how to compare them. the only problem is the error. – da1lbi3 Jun 03 '15 at 20:03

2 Answers2

5

let characters = Array("test") treats the string as a sequence (of characters) and creates an array by enumerating the elements of the sequence. Therefore characters is an array of four Characters, the same that you would get with

let characters : [Character] = ["t", "e", "s", "t"]

So you have two arrays of different element types and that's why you cannot compare them with ==.

If you want an array with a single string "test" then write it as

let characters = ["test"]

and you can compare both arrays without problem.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
1

You just need to specify the type of the second array:

var letteronloc = [String]();
letteronloc.append("test")
let characters: [String] = Array(arrayLiteral: "test")

if (letteronloc == characters) {

}
Remy Cilia
  • 2,573
  • 1
  • 20
  • 31