将Objective-C块转换为Swift闭包

3

我尝试将这个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. 它在代码失败部分后面缺少逗号(,)

3
有什么让你觉得代码有问题吗?它是否出现编译错误?是否出现运行时错误? - Cristik
是的。编译错误。我已经在上面添加了它们。 - Ashish Agarwal
客户端没有'member downloadEntity',可能是问题所在。 - juniperi
#1的错误与逗号无关,clang抱怨一个对象没有downloadEntity成员。client变量是什么数据类型? - Cristik
2个回答

3

试试这个:

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)")
        })

1
这个答案是一个很好的开始,有没有办法添加一些解释来说明你的解决方案是如何解决问题的? - Jonah Graham
只有语法错误。Xcode的自动补全功能将帮助您使用正确的Swift等效方法。因此,AnyObject?应更改为对象名称。就这些。 - Ciprian C

2

您需要切换到新的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块内使用try调用它。

// 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)
// }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接