0

In my code I have 2 separate login types. I have a factory that decides which one to create based on an enum.

Each login type has a different type of credential. Currently my factory method takes just 1 type of credential. How can I generalise my method to accept both an enum for login type with different credential types.

class LoginType1 
{
    var credentials:Credentials
}

class LoginType2 
{
    var credentials:Credentials2
}
enum LoginType 
{
   case : type1,
   case : type2

}

struct Credentials
{
  var username : String,
  var pwd : String
}
struct Creditentials2 
{
  var key : String,
  var id : String
}

public func setupProvider(type: LoginType, credentials: Credentials, ) {
        switch type {
        case .type1:
            provider = LoginType1(credentials: credentials, container: view)
        case .type2:
            provider = LoginType2(credentials: credentials)
        }

    }
Glorfindel
  • 3,167
dubbeat
  • 109
  • 1

1 Answers1

2

My first choice would be to get rid of the enum and have different factory methods. If Swift can do function overloading based on parameter types, that would let you keep the same name for both - but there's usually not much reason to.

If you have good reasons to keep it in a single method, my second choice would be to create a common interface for the credentials, so that the factory method can accept both. That interface should provide enough functionality to be used by the LoginTypes without having to down-cast to the concrete Credentials. Perhaps you could make the Credentials consume LoginTypes instead

If that's not possible, the last option would be to use a "dummy" interface which doesn't expose any functionality, and then down-cast to the types you "know" are allowed. This really is a last resort, and (based just on the example code) I see no reason not to pick the first option in this case.