将objective-c块转换为Swift闭包

问题描述 投票:3回答:2

我试图将这个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. 在代码失败的部分之后,它正在抱怨缺少逗号(,)
objective-c swift
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)")
        })

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)
// }
© www.soinside.com 2019 - 2024. All rights reserved.