-1

I have two arrays

print(">>>>>>>>>>>>>>>>>>>>>>deviceStartList")
dump(deviceStartList)
print(">>>>>>>>>>>>>>>>>>>>>>")

and

print(">>>>>>>>>>>>>>>>>>>>>>deviceEndList")
dump(deviceEndList)
print(">>>>>>>>>>>>>>>>>>>>>>")

It product this result:

enter image description here

I came from a PHP background when I can just call array_diff() , done.

How would one go about doing this?

halfer
  • 19,824
  • 17
  • 99
  • 186
code-8
  • 54,650
  • 106
  • 352
  • 604
  • Have a look at https://stackoverflow.com/questions/24589181/set-operations-union-intersection-on-swift-array. – Martin R Oct 10 '18 at 20:07
  • 1
    Always post code, data, logs, error message, etc as text (not images) so they are searchable, and can be copied when answering. Please [edit] your question and show example data and your expected results. – Ashley Mills Oct 10 '18 at 20:16

3 Answers3

2

If you are looking to do something like set subtraction, Swift has that. See Set operations (union, intersection) on Swift array?.

The title of the SO post above doesn't per se mention the methods subtract(_:) or subtracting(_:), but the content of the accepted answer does cite subtract(_:).

In Swift 4.1, You could do something like:

var deviceStartList = ["12345", "67890", "55555", "44444"]
var deviceEndList = ["12345", "55555"]

var deviceStartSet = Set<String>(deviceStartList)
var deviceEndSet = Set<String>(deviceEndList)

let devicesDiff = deviceStartSet.subtracting(deviceEndSet)

And if you need an array as the final output, you can get that by doing this:

var devicesDiffArray = [String](devicesDiff)

Here is a screenshot of a Playground with this working:

enter image description here

Jacob M. Barnard
  • 1,347
  • 1
  • 10
  • 24
  • As @Sh_Khan's answer says, using the **Swift Standard Library** `Set` operations (...or `NSSet` from **Foundation** if you wanted) would be better. `Set` and `NSSet` are optimized in terms of time complexity. – Jacob M. Barnard Oct 11 '18 at 13:03
1

You can try

let result = deviceStartList.filter { deviceEndList.contains($0) == false }

Also I strongly recommend the Set way as it's internally optimized rather than the usual way

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
1

This is Set way. Hope it's working for you.

var a=["B8D7","38C9","484B", "F4B7"]
var b=["484B","F4B7"]
Set(a).symmetricDifference(Set(b))
E.Coms
  • 11,065
  • 2
  • 23
  • 35