mrfour mrfour - 3 years ago 75
Swift Question

Is it recommended to store constant String in "extension String"

I'm implementing an

Alamofire Router
. And I want to manage my constant url for each api. Normally I create a
to store them like the following code:

private struct API {
static let foo = "domain/models/foo"
static let bar = "doamin/models/bar"

But recently I found it also could be implemented in
extension, like

private extension String {
static let foo = "domain/models/foo"
static let bar = "doamin/models/bar"

In this way, it's easier to me to use it. like

// from
let urlFromStruct: String =

// to
let urlFromExtension: String = .foo

Because extending
means the constants become String's static properties. If I don't omit the
, the code would become

let urlFromExtension: String =

and to prevent these constant will be accessed in other files. I declare the extension with private.

So I wonder is it recommended to implement it by the
way? or any other suggestion is appreciated.

Answer Source

No, this is really not recommended. Even though the type of the values you are storing is string, those values have no logical connection to the String class, so adding them as a type property is a bad idea in my opinion.

Those API endpoints are only connected to your business logic, so they should be stored in a class only related to your business logic and not in a generic class even if you declare them private.

It might also be a good idea to store the endpoints in an enum rather than in a Struct or Class.

private enum API: String {
    case foo = "domain/models/foo"
    case bar = "domain/models/bar"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download