Swift 结果类型转换

我是 swift 的新手,我正在为新的 swift 结果而苦苦挣扎。 所以我有这个功能:

enum LoginOption {
    case signInWithApple
    case emailAndPassword(email: String,password: String,completion: Result<Data,Error>)
}

// func 1:  wrapped with a ui tapped button event:
    private func emailAuthenticationTapped() {
login(with: .emailAndPassword(email: email,password: password,completion: {res in
                // to do 
            }))

// func 2: generic function that routes to the right signIn function based on signIn type:

func login(with loginOption: LoginOption) {
    switch loginOption {
        case let .emailAndPassword(email,password,completion):
               handleSignInWith(email: email,completion: (Result<Data,Error>) -> Void)

// func 3: main async func to handle signin
private func signIn(email: String,completion: @escaping (Result<Data,Error>) -> Void) {
...
}

我收到此错误:

无法将 '((Result) -> Void).Type' 类型的值转换为预期的参数类型 '(Result) -> Void'

terminator83 回答:Swift 结果类型转换

你需要这样称呼它

 signInWith(email: email,password: password) { res in
    // to do 
 }

signIn(email: email,password: password,completion: { res in
   // to do     
})
,

你传递的是类型,但你必须传递一个实例。

解决方案很简单:传递枚举大小写的 completion

func login(with loginOption: LoginOption) {
    switch loginOption {
        case let .emailAndPassword(email,password,completion):
               handleSignInWith(email: email,completion: completion)

并替换

enum LoginOption {
    case signInWithApple
    case emailAndPassword(email: String,password: String,completion: Result<Data,Error>)
}

enum LoginOption {
    case signInWithApple
    case emailAndPassword(email: String,completion: (Result<Data,Error>) -> Void)
}
本文链接:https://www.f2er.com/1987.html

大家都在问