gpt4 book ai didi

arrays - 有没有办法获取对象中属性值的数组?

转载 作者:行者123 更新时间:2023-12-04 09:45:40 25 4
gpt4 key购买 nike

我有一个存储 URL 的对象。在下面的示例中,对象只有 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 返回。

Extension Source


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"]。我想返回值而不是名称。

最佳答案

你可以使用镜像

public final class MyObject: NSObject {
private let firstURL: URL
private let secondURL: URL
private let thirdURL: URL
private let fourthURL: URL

public init(firstURL: URL, secondURL: URL, thirdURL: URL, fourthURL: URL) {
self.firstURL = firstURL
self.secondURL = secondURL
self.thirdURL = thirdURL
self.fourthURL = fourthURL
}

public func values() -> [URL] {
return Mirror(reflecting: self).children.compactMap({ $0.value as? URL })
}
}

let url = URL(string: "https://stackoverflow.com/")!
let myObject = MyObject(firstURL: url, secondURL: url, thirdURL: url, fourthURL: url)
print(myObject.values()
// [https://stackoverflow.com/, https://stackoverflow.com/, https://stackoverflow.com/, https://stackoverflow.com/]

关于arrays - 有没有办法获取对象中属性值的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62129447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com