swift中使用switch语句的布尔函数

swift中使用switch语句的布尔函数,swift,switch-statement,Swift,Switch Statement,我试图使用switch语句得到一个布尔结果,但我猜我的代码中有错误 class func login(username: String , password: String) -> Bool { let url = "http://127.0.0.1:3000/login/"+username+"/"+password Alamofire.request(url).responseJSON { response in

我试图使用switch语句得到一个布尔结果,但我猜我的代码中有错误

class func login(username: String , password: String) -> Bool {
    let url = "http://127.0.0.1:3000/login/"+username+"/"+password
    Alamofire.request(url).responseJSON { response in
        switch response.result {
        case .failure:
            // print(error)
            return false
        case .success:
            // print(value)
            return true
        }
    }
}
用法


您必须使用完成处理程序,因为此代码以异步方式工作。简单地说,您可以“向代码收费”,以便稍后执行。当工作完成时,将触发“完成”。您可以将此类代码还原为通常的方式,但必须使用互斥体,并小心线程阻塞操作。

您需要使用完成处理程序:

class func login(username: String, password: String, completion: (Bool) -> Void) {
    let url = "http://127.0.0.1:3000/login/" + username + "/" + password
    Alamofire.request(url).responseJSON { response in
        switch response.result {
        case .failure:
            completion(false)
            // print(error)
        case .success:
            // print(value)
            completion(true)
        }
    }
}

您应该使用带有Bool参数的完成处理程序,而不是返回值

class func login(username : String , password : String, _ completion: @escaping (Bool) -> ())
现在您可以像这样调用completion,也可以通过声明错误和值来修复案例

然后,在调用completion时,您可以访问其闭包内的Bool参数

Foo.login(username: "", password: "") { success in 
    // print(success)
    ...
}

这是我第一次使用完成处理程序,所以我不知道如何使用它,我想调用我的函数login,这样如果结果为真,我就可以传递到下一个视图controller@LouayBaccary在闭包中而不是我的点传递类似于if success{在这里你可以展示下一个ViewController}我尝试了这段代码,但没有成功API.loginusername:textUsername.text!,密码:textPassword.text!{success in printWelcome}@Louaybacary,您是否在开关中调用completiontrue和completionfalse?这是代码开关响应。结果{case.failure://printerror completionfalse case.success://PrintValue completiontrue}
class func login(username : String , password : String, _ completion: @escaping (Bool) -> ())
switch response.result {
case .failure(let error):
    //print(error)
    completion(false)
case .success(let value):
    //print (value)
    completion(true)
}
Foo.login(username: "", password: "") { success in 
    // print(success)
    ...
}