How do I check in Swift if two arrays contain the same elements regardless of the order in which those elements appear in?

前端 未结 8 1223
臣服心动
臣服心动 2020-12-02 22:20

Let\'s say there are two arrays...

var array1 = [\"a\", \"b\", \"c\"]
var array2 = [\"b\", \"c\", \"a\"]

I\'d like the result of the compar

8条回答
  •  广开言路
    2020-12-02 22:37

    you can do something like this:

      array1.sortInPlace()
      array2.sortInPlace()
    
      print(array1,array2)
    
      if array1 == array2 {
        print("equal")
      } else {
      print("not equal") 
      }
    

    and if don't want change origional array we can do

     let sorted1 = array1.sort()
     let sorted2 = array2.sort()
    
      if sorted1 == sorted2 {
        print("equal")
      }else {
        print("not equal")
      }
    

提交回复
热议问题