Monday, February 19, 2024
HomeiOS Developmentios - Easy methods to regenerate code to instantiate object from occasion...

ios – Easy methods to regenerate code to instantiate object from occasion in Swift


For unit testing, I want to generate the minimal of swift code that’s wanted as a way to re-create an occasion.

For instance, I’ve bought the next struct:

struct Consumer {
    enum Position {
        case admin, advertising, tester, developer, gross sales
    }

    let identify: String
    let e mail: String

    let icon: URL?
    let roles: [Role]

    public init(identify: String, e mail: String, icon: URL? = nil, roles: [Role]? = nil) {
        self.identify = identify
        self.e mail = e mail
        self.icon = icon
        self.roles = roles
    }
}

And at runtime I’ve bought this person, created from varied sources:

â–¿ Consumer
  - identify: "John Appleseed"
  - e mail: "[email protected]"
  - icon: nil
  â–¿ roles: Non-compulsory([User.Role.admin])
    â–¿ some: 1 component
      - Consumer.Position.admin

I want to generate the swift code that I must re-create this person in a unit take a look at.

Reflection offers me begin, nevertheless it’s not very best:

print(String(reflecting: person))

Consequence:

MyLibrary.Consumer(identify: "John Appleseed", e mail: "[email protected]", icon: nil, roles: Non-compulsory([MyLibrary.User.Role.admin]))

It isn’t very best as a result of:

  • Every type prefixed by their module
  • Specific optionals
  • Included nil properties
  • No fairly formatting with indentation

What I am searching for is one thing like this:

Consumer(
    identify: "John Appleseed",
    e mail: "[email protected]",
    roles: [.admin]
)

I may conform my sorts to CustomReflectable to enhance the optionals and nil‘s:

extension Consumer: CustomReflectable {
    public var customMirror: Mirror {
        var kids: [(label: String?, Any)] = [
            ("name", name as Any),
            ("email", email as Any)
        ]

        if let icon {
            kids.append(("icon", icon))
        }

        if let roles, !roles.isEmpty {
            kids.append(("roles", roles))
        }

        return Mirror(
            self,
            kids: kids,
            displayStyle: .struct
        )
    }
}

And maybe string change the lib identify?

let end result = String(reflecting: person).replacingOccurrences(of: "MyLibrary.", with: "")
print(end result)

Consequence:

Consumer(identify: "John Appleseed", e mail: "[email protected]", roles: [User.Role.admin])

This already improves it so much however the enum worth nonetheless has a prolonged sort, and the code has no indentation.

Additionally having to evolve all the kinds to CustomReflectable and preserve it might be fairly some work.

Any tips about the way to enhance this?



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments