- 定义操作符:
//
// AsyncTask.swift
//
// Created by lenbo lan on 2021/2/5.
//
typealias Action = () -> Void
typealias AsyncTask = (_ act: @escaping Action) -> Void
// 定义优先级
precedencegroup AsyncOperater {
associativity: left
higherThan: AssignmentPrecedence
}
// 定义操作符
infix operator +>: AsyncOperater
func +>(left:@escaping AsyncTask, right:@escaping AsyncTask) -> AsyncTask {
return { complete in
left {
right {
complete()
}
}
}
}
- 使用:
func uploadProfileImage(complete: @escaping Action) {
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(uploadData, withName: "imgUploader", fileName: "\(filename).jpg", mimeType: "image/jpeg")
}, to: server_api.upload)
.uploadProgress { progress in
print(CGFloat(progress.fractionCompleted)*100)
}
.responseJSON { response in
debugPrint(response)
switch response.result {
case .success(let value):
let dict = JSON(value)
let imageUrl = dict["image"].stringValue
print("image url: \(imageUrl)")
UserDefaultsManager.shared.profileImageUrl = imageUrl
// 回调
complete()
case .failure:
print("upload image failure")
return
}
}
}
func regist(complete: @escaping Action) {
let parameters = ["name": fullName,
"username": username,
"email": email,
"profileImageUrl": profileImageUrl,
"password": password]
AF.request(server_api.regist, method: .post, parameters: parameters)
.responseJSON { response in
print("Response JSON: \(response.value ?? "")")
// 回调
complete()
}
}
// 执行操作
let taskRegist = uploadProfileImage +> regist
taskRegist {
DispatchQueue.main.async {
print("sign up complete")
}
}
- 参考于:
http://www.voidcn.com/article/p-fcxrweyk-ym.html
https://docs.swift.org/swift-book/ReferenceManual/Declarations.html
https://developer.apple.com/documentation/swift/swift_standard_library/operator_declarations
网友评论