我正在练习Swift,我有以下代码:
import Foundation
@objc class Model {
typealias completionBlock = (data: NSData?, error: NSError?) -> Void
func saveEmailAccount(email: String, password: String, mailServer: String, mailPort: Int, completionHandler: completionBlock) -> Void {
let httpPOSTBody = ["email" : email, "password" : password, "mailServer" : mailServer, "mailPort" : mailPort]
let urlRequest = NSMutableURLRequest()
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.HTTPMethod = "POST"
urlRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(httpPOSTBody, options: nil, error: nil)
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
session.dataTaskWithURL(urlRequest.URL!, completionHandler: { (data: NSData!, response:NSURLResponse!, error: NSError!) -> Void in
completionBlock(data, error)
})
}
}
但是我得到" completionBlock不能用'(NSData!,NSError!)' 构建。不确定我做错了什么
答案 0 :(得分:2)
您尝试使用拼写错误调用completionHandler
completionBlock
更改块调用:
completionBlock(data, error)
为:
completionHandler(data, error)
Apple建议(并且我同意)类型名称的一个原因应该是大写字母的大写字母和变量名称。
另一个问题是通过将类型别名定义为:
typealias completionBlock = (data: NSData?, error: NSError?) -> Void
您指定应使用命名参数定义和调用完成块:
completionHandler(data:data, error:error)
或者,将类型别名更改为:
typealias completionBlock = (NSData?, NSError?) -> Void
哪个更符合我见过的规范。