首页 > 解决方案 > 有没有办法获取对象中属性值的数组?

问题描述

我有一个存储URLs 的对象。在下面的示例中,对象只有 4 个属性,但在我的情况下还有更多,所以我想知道有没有更优雅的方法来做到这一点。


public final class MyObject: NSObject {

  private let firstURL: URL
  private let secondURL: URL
  private let thirdURL: URL
  private let fourthURL: URL

  public func values() -> [URL] {
    return // <--- I need to return URLs from properties like [firstURL, secondURL, thirdURL, fourthURL]
  }
}

我找到了一个扩展NSObject名,可以将属性名称的数组作为String.

扩展源


public extension NSObject {

  //
  // Retrieves an array of property names found on the current object
  // using Objective-C runtime functions for introspection:
  // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html
  //
  func propertyNames() -> Array<String> {
    var results: Array<String> = []

    // retrieve the properties via the class_copyPropertyList function
    var count: UInt32 = 0
    let myClass: AnyClass = classForCoder
    let properties = class_copyPropertyList(myClass, &count)

    // iterate each objc_property_t struct
    for i in 0..<count {
      if let property = properties?[Int(i)] {
        // retrieve the property name by calling property_getName function
        let cname = property_getName(property)

        // covert the c string into a Swift string
        results.append(cname.debugDescription)
      }
    }

    // release objc_property_t structs
    free(properties)

    return results
  }
}

但它返回属性名称的数组,如["firstURL", "secondURL", "thirdURL", "fourthURL"]. 我想返回值而不是名称。

标签: arraysswift

解决方案


您可以使用Mirror并遍历所有内容children

struct Foo {
    let a: String
    let b: String
    let x: Int

    func propsAsArray() -> [Any] {
        let mirror = Mirror(reflecting: self)
        return mirror.children.map { $0.value }
    }
}


let f = Foo(a: "foo", b: "bar", x: 42)
print(f.propsAsArray()) // ["foo", "bar", 42]

推荐阅读