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.

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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
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 ?? ""}
}

Comments

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.