Skip to main content
 首页 » 操作系统

generics之Swift 泛型、枚举和装箱

2024年01月01日41soundcode

对不起,标题...不知道该取什么名字。

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 
    } 
} 

我得到的错误是:

Cannot convert the expression's type 'Box' to type '[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]> .