gpt4 book ai didi

Swift 泛型类初始化器

转载 作者:行者123 更新时间:2023-11-28 06:51:50 27 4
gpt4 key购买 nike

我发现在 swift 中设计结果类有问题

struct Result<T>{
private let data: T?
let error: NSError?
var isSuccess: Bool {
get {
return data != nil
}
}

init(data: T) {
self.data = data
self.error = nil
}

init(error: NSError) {
self.data = nil
self.error = error
}
}

用法应该是这样的

Result(data: "something") // T as string

当我想传递错误时出现问题

Result(error: errorFromSomewhere) //T is not specified

下面是真实的应用用法:

class ParseRegistrationProvider: RegistrationProvider {
func register(model: RegistrationForm) -> Promise<Result<String>> {
return Promise { accept, reject in
let user = PFUser()
user.username = model.nickName
user.password = model.password
user.email = model.emailAdreess
user.signUpInBackgroundWithBlock({ (isSuccess, error) -> Void in
if isSuccess {
accept(Result(data: "OK"))
} else {
var errorResult = Result(error: error!) //causes error
reject(errorResult)
}
})
}
}
}

“errorResult”导致编译器错误:

Generic parameter T could not be inferred

更新:此方法正常工作:

Result<String>(error: errorFromSomewhere)

最佳答案

我想建议像这样对 Result 使用变体类型,因为它更紧凑并且可以自然地用于模式匹配:

enum Result<T>{
case Data(T?)
case Error(NSError)
var isSuccess: Bool{
get{
switch self{
case .Data(_?):
return true
default:
return false
}
}
} }

你的代码可能会变成这样:

class ParseRegistrationProvider: RegistrationProvider {
func register(model: RegistrationForm) -> Promise<Result<String>> {
return Promise { accept, reject in
let user = PFUser()
user.username = model.nickName
user.password = model.password
user.email = model.emailAdreess
user.signUpInBackgroundWithBlock({ (isSuccess, error) -> Void in
if isSuccess {
accept(Result<String>.Data("OK"))
} else {
var errorResult = Result<String>(error: error!) //causes error
reject(errorResult)
}
})
}
}

关于Swift 泛型类初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34656819/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com