arrays - 有没有办法获取对象中属性值的数组?
问题描述
我有一个存储URL
s 的对象。在下面的示例中,对象只有 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"]
. 我想返回值而不是名称。
解决方案
您可以使用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]
推荐阅读
- python - Getting AttributeError: __exit__ when working with Tensorflow and MNIST data
- c# - What is wrong with my aproach for detecting open serial port?
- sql - Comparing two latest rows and return true or false based on location_id
- excel - application function using index small if in order to find more than one matching result
- c# - 为什么我没有得到 EnvironmentVariable
- .net - Firebase 云函数:你可以从 dll 调用函数吗?
- sass - Is the a way to create a large list in SCSS?
- vectorization - Matrix multiplication with vectorization in c++
- java - 如何更改 JComboBox 的字体
- php - 实体类映射无效