斯威夫特泛型和枚举与拳击
对不起,标题...不知道该怎么命名它。斯威夫特泛型和枚举与拳击
typealias JSON = AnyObject
typealias JSONArray = Array<AnyObject>
protocol JSONDecodable {
class func decode(json: JSON) -> Self?
}
final class Box<T> {
let value: T
init(_ value: T) {
self.value = value
}
}
enum Result<A> {
case Success(Box<A>)
case Error(NSError)
init(_ error: NSError?, _ value: A) {
if let err = error {
self = .Error(err)
} else {
self = .Success(Box(value))
}
}
}
func decode<T: JSONDecodable>(jsonArray: JSONArray?) -> Result<[T: JSONDecodable]> {
if let jsonArray = jsonArray {
var resultArray = [JSONDecodable]()
for json: JSON in jsonArray {
let decodedObject: JSONDecodable? = T.decode(json)
if let decodedObject = decodedObject {
resultArray.append(decodedObject)
} else {
return Result.Error(NSError()) //excuse this for now
}
}
return Result.Success(Box(resultArray)) // THE ERROR IS HERE !!!!
} else {
return Result.Error(NSError()) //excuse this for now
}
}
我得到的错误是:
不能转换表达式的类型“框中为键入 '[T:JSONDecodable]'
可能有人请解释为什么我不能做到这一点,以及我如何解决它。
感谢
您在声明函数为返回Result<[T: JSONDecodable]>
,其中泛型类型为[T: JSONDecodable]
,即一本字典。
这里:
return Result.Success(Box(resultArray)) // THE ERROR IS HERE !!!!
您提供Box<Array>
到Result.Success
,但按照函数声明,它需要一个Box<Dictionary>
。
我不知道错误是在函数声明或resultArray
型,顺便说一句,我发现最快的解决方法是改变函数声明:
func decode<T: JSONDecodable>(jsonArray: JSONArray?) -> Result<[JSONDecodable]>
返回Result<[JSONDecodable]>
而不是Result<[T: JSONDecodable]>
。
LOL ...!不能相信这是我最后一个问题的错误!也许我需要另一杯咖啡...我需要开始付钱给你。再次感谢。 – bandejapaisa 2014-11-24 12:15:30
LOL我现在意识到这是同一个错误,我认为这是一个真正的字典这一次;-) – Antonio 2014-11-24 12:18:42
这是解决我的方法失败:
func decode<T: JSONDecodable>(jsonArray: JSONArray?) -> Result<[T]> {
if let jsonArray = jsonArray {
var resultArray = [T]()
for json: JSON in jsonArray {
let decodedObject: T? = T.decode(json)
if let decodedObject = decodedObject {
resultArray.append(decodedObject)
} else {
return Result.Error(NSError()) //excuse this for now
}
}
return Result.Success(Box(resultArray))
} else {
return Result.Error(NSError()) //excuse this for now
}
}
你的问题的标题把我吓坏了:我还以为你找打:) – 2014-11-24 12:06:00