将objective-c块转换为Swift闭包

时间:2015-11-05 16:00:12

标签: 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. 在代码失败的部分
  3. 之后,它正在抱怨缺少逗号(,)

2 个答案:

答案 0 :(得分: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 :(得分: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块中尝试调用它。

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