ios – Huge configuration object as a paremeter in Swift?

[ad_1]

In JavaScript/TypeScript we’ve this sample that’s usually utilized in libraries the place you’ve gotten one non-obligatory parameter because the final operate argument which defaults to some default configuration. It seems like the next:

const smth = someLibrary("requiredParameter", {
  someOptionalProperty: true,
  // ...different choices out there, however not required to be supplied right here.
});

On the library facet it could look one thing like this:

export const someLibrary = (requiredParameter: string, choices?: Choices) => {
  const opts = { ...defaultOptions, ...choices };

  // Right here `opts` could have the default properties merged with those that you simply supplied.
}

Now, in Swift, from what my 2-3 yr expertise has instructed me, if you wish to do one thing comparable it’s a must to make a struct with all of the configuration parameters after which mutate the defaults after instantiating the struct. This is able to look one thing like the next:

struct Choices {
  var option1: Double = 2.0
  var option2: Int = 1
  // ...and so forth
}

public func someLibrary(_ requiredParameter: String, choices: Choices?) {
  // ...
}

let opts = Choices()
opts.someParameter = "Overriding the values right here"

let outcome = someLibrary("requiredParameter", choices: )

The issue

There are a few issues with the Swift implementation that JavaScript does very effectively:

  1. Default choices override, however simply the fields that have been modified – I have not been capable of replicate this in swift with an answer that’s at the least shut in elegancy.
  2. Partial override of the choices – the method in Swift that I used to be utilizing is to have an initializer for the struct with all non-obligatory parameters, however the initializers grow to be big for large configurations.

The Query

Now the query is – how shut can I get to the JavaScript model utilizing Swift?

Perhaps there is a sample or a operate that I am lacking that might try this for me?

The objective for me is to not have big boilerplate to make my library customisable.

[ad_2]

Leave a Reply