Raja
Raja

Reputation: 177

In Swift, is it possible to get all the **static** properties from a struct?

I have a struct with a protocol like,

protocol Page {
    func getAllProperties () -> [String: Any] 
}

extension Page {
    public func getAllProperties () -> [String: Any] {
        var result: [String: Any] = [:]
        let mirror = Mirror(reflecting: self)
        print(mirror)
        for (labelMaybe, valueMaybe) in mirror.children {
            print(labelMaybe)
            guard let label = labelMaybe else {
                continue
            }

            result[label] = valueMaybe
        }

        return result
    }

}


struct Test: Page {
    static let aa = "aaaaa"
    let bb = "bbbb"
}

Here Test().getAllProperties() returns only bb, it omits the static property!!!

I want that getAllProperties() return those static property too!

is there any way for it?

Upvotes: 8

Views: 1889

Answers (2)

Oz Shabat
Oz Shabat

Reputation: 1622

If you're willing to turn your struct into a class then that's possible.

You can do this if you'll incorporate some objc during runtime. It doesn't even mean that you need to create objc class, you just need to write some objc c code in your Swift file.

Please read Andrea Mugnaini answer here

The idea is to use objc c to read the class properties and present them using Swift.

Notice though, you'll need to mark your class as NSOjbect and your static constants with the prefix "@objc static".

an example:

class SomeRandomClass: NSObject {
    @objc public static let my_cool_prop_name = "propValue"
}

static func reflectClass() {
    var count: CUnsignedInt = 0
    let methods = class_copyPropertyList(object_getClass(BtnsBank.self), &count)!
    for i in 0 ..< count {
        let selector = property_getName(methods.advanced(by: Int(i)).pointee)
        if let key = String(cString: selector, encoding: .utf8) {
            print("name: \(key), value: \(res ?? "")")
        }
    }

Again, taken from here

Upvotes: 1

Lily Ballard
Lily Ballard

Reputation: 185711

To the best of my knowledge, the answer is no. Sorry. Even getting a Mirror on the type(of: self) doesn't end up having any children.

Upvotes: 6

Related Questions