How to loop over struct properties in Swift?

前端 未结 6 1076
情话喂你
情话喂你 2020-12-13 04:16

Is it possible to iterate over properties of a struct in Swift?

I need to register cells-reuse identifiers in a view controller that makes use of many different cel

6条回答
  •  死守一世寂寞
    2020-12-13 05:12

    Now there's a much easier way to do this:

    1: Create an Encodable protocol extension:

    extension Encodable {
        var dictionary: [String: Any]? {
            guard let data = try? JSONEncoder().encode(self) else { return nil }
            return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
        }
    }
    

    2: Make your struct/class conform to Encodable protocol

    struct MyStruct: Encodable {...}
    class MyClass: Encodable {...}
    

    And then you can get a Dictionary representing your struct/class instance at any time:

    var a: MyStruct
    var b: MyClass
    
    print(a.dictionary)
    print(b.dictionary)
    

    And then you can loop through the keys:

    for (key, value) in a.dictionary { ... }
    for (key, value) in b.dictionary { ... }
    

提交回复
热议问题