ios – Swift ObservableObject implementation with generic inference


I need to admit my data of swift is proscribed, and I can not wrap my head round this drawback.

I’ve outlined this protocol, so I can use completely different auth suppliers in my app.

protocol AuthRepository {
    associatedtype AuthData
    associatedtype AuthResponseData
    associatedtype RegistrationData
    associatedtype RegistrationResponseData
    
    func login(with knowledge: AuthData) async throws -> AuthResponseData?
    
    func register(with knowledge: RegistrationData) async throws -> RegistrationResponseData?
}

and an implementation for my server

struct MyServerAuthData {
    let e-mail: String
    let password: String
}

struct  MyServerAuthResponseData {
    let token: String
}

struct  MyServerRegistrationData {
    let e-mail: String
    let password: String
    let identify: String
}

actor AuthRepositoryImpl: AuthRepository {
    func login(with knowledge: MyServerAuthData) async throws ->  MyServerAuthResponseData? {
        ...
    }
    
    func register(with knowledge:  MyServerRegistrationData) async throws -> Void? {
        ...
    }
}

To make use of throughout the app, I’ve created this ViewModel

@MainActor
ultimate class AuthViewModel: ObservableObject {
    non-public let repository: T

    init(repository: T) {
        self.repository = repository
    }

    func login(knowledge: T.AuthData) async throws -> T.AuthResponseData? {
        strive await repository.login(with: knowledge)
    }

    func register(with knowledge: T.RegistrationData) async throws {
        strive await repository.register(with: knowledge)
    }
}

outlined within the app as

@primary
struct MyApp: App {
    @StateObject var authViewModel = AuthViewModel(repository: AuthRepositoryImpl())

    var physique: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(self.authViewModel)
        }
    }
}

and consumed as

@EnvironmentObject non-public var authViewModel: AuthViewModel

However with this code, the entire idea of getting a generic implementation for the auth repository is ineffective, as a result of altering the AuthRepostory might want to search and substitute AuthViewModel throughout all of the app.

I’ve skilled this instantly making a MockAuthImpl to make use of with #Preview, and the preview crashed as a result of it defines AuthViewModel(repository: MockAuthImpl()) however the view expects AuthViewModel.

There’s a higher approach to do this?

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles