将objective-c块转换为Swift闭包

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将objective-c块转换为Swift闭包相关的知识,希望对你有一定的参考价值。

我试图将这个Objective-C块转换为Swift:

[self.client downloadEntity:@"Students" withParams: nil success:^(id response) {
      // execute code
}
failure:^(NSError *error) {
    // Execute code

}];

这是我在Swift中的代码,但语法似乎有点偏差:

    client.downloadEntity("Students", withParams: nil, success:  {(students: [AnyObject]!) -> Void in
        print("here")
        },  failure:  { (error: NSError!) -> Void! in
            print ("here")
     }

这给了我一些编译错误:

  1. 'AnyObject'的值没有成员'downloadEntity'
  2. 在代码失败的部分之后,它正在抱怨缺少逗号(,)
答案

试试这个:

client.downloadEntity("Student", withParams: nil,
        success: { (responseObj) -> Void in
            print("success: (responseObj)")
        },

        failure: { (errorObj) -> Void in
            print("treat here (in this block) the error! error:(errorObj)")
        })
另一答案

您需要切换到新的Swift错误语法,并且还可以使用尾随闭包。我不得不在示例中使用bool来显示如何调用成功闭包,否则会抛出错误。

var wasSuccessful = true // This is just here so this compiles and runs

// This is a custom error type. If you are using something that throws an
// NSError, you don't need this.
enum Error:ErrorType {
    case DownloadFailed
}

// Hopefully you have control over this method and you can update
// the signature and body to something similar to this:
func downloadEntity(entityName: String, success: ([AnyObject]) -> Void)  throws {
    let students = [AnyObject]()

    // download your entity
    if wasSuccessful {
        // Call your success completion handler
        success(students)
    }
    else {
        throw Error.DownloadFailed
    }
}

如果你有一个可以抛出错误的函数,你需要在do / catch块中尝试调用它。

// Calling a function that can throw
do {
    try downloadEntity("Students") { students in 
        print("Download Succeded")
    }
}
catch Error.DownloadFailed {
    print("Download Failed")
}
// If you are handling NSError use this block instead of the one above
// catch let error as NSError {
//     print(error.description)
// }

以上是关于将objective-c块转换为Swift闭包的主要内容,如果未能解决你的问题,请参考以下文章

将 Objective-C 方法转换为 Swift [关闭]

Swift:闭包

将objective-c面向块的api转换为android

swift闭包新手详解(新手必看)

Swift学习笔记-继续学习闭包

Swift学习笔记-继续学习闭包