ios - 将函数 void 移动到 bool Swift

标签 ios swift

我是 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/

相关文章:

ios - 如何将 String.UTF8View.Index 转换为 String.CharacterView.Index?

ios - TagListView单选swift 4

ios - 使用 arc4random 更改按钮的框架?

ios - 如何检测当前用于文本输入的自定义键盘(ios 8)

ios - PHAsset 视频压缩 iOS swift

ios - glTexSubImage2D 在 ios7 上运行缓慢

UiView 中的 IOS swift avplayer 我怎样才能让它工作

iphone - 在不减慢 xcode 的情况下在 iPhone 应用程序中包含许多图像

ios - 在 iOS 9 中滚动 UITableView 会导致标签重叠

swift - Cocoa中的自定义View在设置AutoLayout Constraints后无法绘制