Charles
Charles

Reputation: 61

Swift: Checking if a member exist in a struct

For the following code, how can I check if a member "b" or "f" exist for myArray?

struct example {

    var a: String!
    var b: Bool!
    var c: Bool!
    var d: String!

}

var myArray = [example]!

For example, if I check if member "f" exists, I would like something to return "false" or "nil"; and if I check if "b" exists, I would like to receive "true".

Thanks!

Upvotes: 0

Views: 2679

Answers (3)

MH175
MH175

Reputation: 2334

Using Mirror.

let example = Example()
let containsB = Mirror(reflecting: example).children.contains { $0.0 == "b" } // true
let containsF = Mirror(reflecting: example).children.contains { $0.0 == "f" } // false

let examples = [Example(), Example(), Example()]
let containsA = examples.filter {
    Mirror(reflecting: $0).children.contains { $0.0 == "a" }
}.isEmpty == false // true

Upvotes: 1

Gsp
Gsp

Reputation: 719

As others have commented, there are other problems with your example, but assuming you know and are just throwing out a quick and dirty sample to illustrate your question, you could do something a bit like this:

if let bExists = myArray.b {
  return true
} else if let fExists = myArray.f {
  return false // or return nil, or whatever you want to do if `f exists.
}

Upvotes: -1

Charles Srstka
Charles Srstka

Reputation: 17060

Unlike Objective-C, Swift does not have the dynamic mechanisms to do things like this. So the answer is that no, you cannot check for members by name in this way, unless you are working with members of an NSObject subclass which are marked with the @objc attribute.

Upvotes: 1

Related Questions