问题描述
func CreateProjectPossibleAccount(possibleAccount: ProjectPossibleAccount) -> Data {
var dataToReturn: Data?
self.dispatchGroup.enter()
do {
var request = getUrlRequestFor(RequestType.post)
request.httpBody = try JSONEncoder().encode(possibleAccount)
URLSession.shared.dataTask(with: request) {
(data,response,err) in
guard let data = data else {return}
dataToReturn = data
self.dispatchGroup.leave()
}.resume()
} catch {
print(error.localizedDescription)
}
self.dispatchGroup.wait()
return dataToReturn!
}
func CreateMaterialIssueItem(item: NewMaterialIssueItem) -> Data {
var dataToReturn: Data?
self.dispatchGroup.enter()
do {
var request = getUrlRequestFor(RequestType.post)
request.httpBody = try JSONEncoder().encode(item)
URLSession.shared.dataTask(with: request) {
(data,err) in
guard let data = data else {return}
dataToReturn = data
self.dispatchGroup.leave()
}.resume()
} catch {
print(error.localizedDescription)
}
self.dispatchGroup.wait()
return dataToReturn!
}
我有几个类似的功能,其中唯一真正的区别是我创建的自定义类型。有没有办法仅将此函数命名为Post(item:T)并传入所有唯一类型?
解决方法
您可以使用泛型来避免代码重复。在下面的示例中,我假设ProjectPossibleAccount
和NewMaterialIssueItem
实现了Decodable
协议,并且RequestType
是一个枚举。 dispatchGroup
也可能成为该方法的参数。
func request<T: Encodable>(item: T,requestType: RequestType) -> Data {
var dataToReturn: Data?
self.dispatchGroup.enter()
do {
var request = getUrlRequestFor(requestType)
request.httpBody = try JSONEncoder().encode(item)
URLSession.shared.dataTask(with: request) {
(data,response,err) in
guard let data = data else {return}
dataToReturn = data
self.dispatchGroup.leave()
}.resume()
} catch {
print(error.localizedDescription)
}
self.dispatchGroup.wait()
return dataToReturn!
}
,您可以这样调用方法:
let possibleAccount: ProjectPossibleAccount = ProjectPossibleAccount()
let data = request(item: possibleAccount,requestType: .post)
上一个示例的另一种方法(并且因为它很简单)是将item
param数据类型指定为Encodable
,如下所示:
func request(item: Encodable,requestType: RequestType) -> Data