Search code examples
swiftalamofire

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 struct 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 String 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 = API.foo

// to
let urlFromExtension: String = .foo

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

let urlFromExtension: String = String.foo

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 extension way? or any other suggestion is appreciated.


Solution

  • 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 type only related to your business logic and not in a "generic" type 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 {
        static let foo = URL(string: "domain/models/foo")!
        static let bar = URL(string: "domain/models/bar")!
    }