我是 Swift 的新手。我需要将以下方法更改为一个 bool 函数,如果连接正常,它将返回 true,如果出现问题,则返回 false。谢谢
func test() {
var configuration = SessionConfiguration()
configuration.host = "ftp://ftp.mozilla.org:21"
configuration.username = "optimus"
configuration.password = "rollout"
configuration.encoding = NSUTF8StringEncoding
_session = Session(configuration: configuration)
_session.list("/") {
(resources, error) -> Void in
println("List directory with result:\n\(resources), error: \(error)\n\n")
}
}
最佳答案
因为 _session.list("/")
有一个回调,它是异步的,你可以这样做:
func test(_ completion: (Bool) -> Void) {
// ...
_session.list("/") { (resources, error) -> Void in
println("List directory with result:\n\(resources), error: \(error)\n\n")
guard error == nil else {
completion(false) // failed
return
}
completion(true) // succeed
}
}
所以你可以这样调用它:
test() { (hasSucceeded: Bool) -> Void in
if hasSucceeded {
// Do what you want
} else {
// Failed
}
}
关于ios - 将函数 void 移动到 bool Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38721721/