1

I have an NSObject with some properties as in:

public class Contact: NSObject {

var first: String = ""
var last: String = ""
var title: String = ""
//and so forth
}

Is there a simple way to get the values of the object properties for a single instance of the object, ie one Contact, into an array such as:

{"Bob","Smith","Vice President"}

I can't seem to find a straightforward way to do this. Thanks in advance for any suggestions.

user6631314
  • 1,751
  • 1
  • 13
  • 44

2 Answers2

1

The caveman way:

public class Contact: NSObject {

  var first: String = ""
  var last: String = ""
  var title: String = ""

  var values: [String] {
    return [first, last, title]
  }
}

A more useful way, which allows you to serialize to NSKeyedArchiver, JSONEncoder, or whatever:

public class Contact: NSObject {

  var first: String = ""
  var last: String = ""
  var title: String = ""

  var values: NSDictionary {
    return [
      "first": first,
      "last": last,
      "title": title
    ]
  }
}

Either way, the simplest method is to manually scrape out the state properties you are interested in.

ouni
  • 3,233
  • 3
  • 15
  • 21
  • The class is in another file but I was able to use the manual method to create an array from the object. Wish I could give extra +1 for caveman reference – user6631314 Jun 05 '18 at 14:42
0

The best way to find the values of the Object's properties is to use the Mirror apis provided by apple. You can get properties values as

Example Code

public class Contact: NSObject {
var first: String = ""
var last: String = ""
var title: String = ""
//and so forth

var values: [String] {
    return Mirror(reflecting: self).children.map {$0.value as? String ?? ""}
}
avinash pandey
  • 1,321
  • 2
  • 11
  • 15