1

I have the following Structure:

struct MyStrict {
    let prop1: String
    let prop2: [String: NSData]
    let prop3: [String]

    init (prop11: String, prop22: [String : NSData], prop33: [String]) {
        prop1 = prop11
        prop2 = prop22
        prop3 = prop33
    }
}

The instance structure is placed in the Array. What I need to do is to find if the structure with those properties are in the array or not. I need to compare data.

Something like this:

var arr = [MyStrict]()

var str1 = MyStrict(prop11: "test1", prop22: ["aa": NSData()], prop33: ["bb"])
arr.append(str1)

var str2 = MyStrict(prop11: "test2", prop22: ["bb": NSData()], prop33: ["cc"])
arr.append(str2)

var str3 = MyStrict(prop11: "test3", prop22: ["cc": NSData()], prop33: ["dd"])
arr.append(str3)

var str4 = MyStrict(prop11: "test1", prop22: ["aa": NSData()], prop33: ["bb"]) // has the same data as str1
arr.append(str4)

As you can see the str1 and str4 have the same data. So str4 should not be add to the Array.

My question what is the right way to do this?

1 Answer 1

2

You need to add the protocol Equatable to your Struct

struct MyStrict: Equatable {
...
}

Then you have to add the == operator under the class like this :

func == (lhs: MyStrict, rhs: MyStrict) -> Bool {
  if lhs.prop1 == rhs.prop1 && lhs.prop3 == rhs.prop3 && lhs.prop2 == rhs.prop2 {
    return true
}

  return false
}

Now, to know if your struct is already in the array you just have to use this :

if contains(arr, str4) == true {
  println("already in")
} else {
  println("Not in")
}
Sign up to request clarification or add additional context in comments.

2 Comments

Or just if contains(arr, str4) ...
I edited the answer. Contains fits the question needs better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.