简体   繁体   English

Swift 3-具有静态方法的协议,具有泛型类型的实例方法,可选的'.Type'参数

[英]Swift 3 - Protocol with static methods, instance method with generic types, optional '.Type' parameter

I'm trying do implement some networking code that will get json at an endpoint, then parse the result into CoreData objects. 我正在尝试实现一些网络代码,这些代码将在端点处获取json,然后将结果解析为CoreData对象。

I defined a protocol JSONParsable that some of my CoreData object classes conform to. 我定义了一些CoreData对象类所遵循的协议JSONParsable。

import SwiftyJSON
import CoreData

protocol JSONParsable {

// you validate the json response from the server to make sure it has everything you expect to function properly
static func validate(_ jsonResponse: JSON) throws

// now parse the jsonResponse
static func parseAll<T: NSManagedObject>(_ jsonResponse:JSON, into context:NSManagedObjectContext) -> [T]!

// describes how to parse one data object in a json response
static func parse<T: NSManagedObject>(_ jsonObject:JSON, into context:NSManagedObjectContext) -> T?

}

Why? 为什么? Because they are utility methods for objects of that type. 因为它们是该类型对象的实用程序方法。 So the "GET Objects" method on my networking client "Manager" looks basically like this: 因此,网络客户端“ Manager”上的“ GET Objects”方法基本上如下所示:

private func get<T:JSONParsable>(_ urlString: URLConvertible, expectedObjectType:T.Type?, completion: @escaping (_ success: Bool) -> Void)

The problem is, if expectedObjectType is ever nil, the compiler complains with an error: 问题是,如果expectedObjectType为零,则编译器会报错:

Generic parameter 'T' could not be inferred

I'm not sure how to solve this. 我不确定该如何解决。 I guess I've taken a wrong approach somewhere, being still from the Objective-C world. 我想我在某个地方采用了错误的方法,但仍然来自Objective-C世界。 Would appreciate some help, including a different approach if necessary. 希望能提供一些帮助,如有必要,可以使用其他方法。

I am basically saying "get json at a specific URL and use a specific class extension to parse it." 我基本上是说“在特定的URL获取json并使用特定的类扩展来解析它”。

I'm also thinking I could implement a 'Dummy Class' and provide that? 我还认为我可以实现“虚拟课程”并提供? Seems a little dirty, but aren't we all a little dirty from time to time? 似乎有点脏,但是我们不是时不时都有点脏吗? :) :)

The answer is not exactly an answer, only to say I changed the approach. 答案不完全是一个答案,只是说我改变了方法。 I made an explicit parser object, changed the protocol definition to instance methods, and the parser object remains a member of a 'service' object, that belongs to the networking client. 我做了一个明确的解析器对象,将协议定义更改为实例方法,并且解析器对象仍然是属于网络客户端的“服务”对象的成员。

It works well this way because json parsing relates to the endpoint that provides that JSON. 之所以如此有效,是因为JSON解析与提供JSON的端点有关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM