Swift协变泛型

时间:2016-03-08 08:52:54

标签: ios swift generics protocols

以下是我想要实现的一个例子:

{
  "movies": [
    {
      "movieTitle": "True Lies",
      "Cert": "15",
      "Released": "1987",
    },
     {
      "movieTitle": "Scary Movie",
      "Cert": "18",
      "Released": "1997",
    },

甚至更简单:

response = requests.get('https://api.foo.com/movies/all', headers=headers)
json_object = json.loads(response.text)
print json_object

如何设法protocol SomeType {} class SomeClass: SomeType {} struct SomeGenericStruct<A> { typealias E = A } func take(someType: SomeGenericStruct<SomeType>) {} let concreteGenericStruct1: SomeGenericStruct<SomeType> = SomeGenericStruct<SomeType>() let concreteGenericStruct2: SomeGenericStruct<SomeClass> = SomeGenericStruct<SomeClass>() take(concreteGenericStruct1) take(concreteGenericStruct2) // much no work, very repair. wow. 提供let concreteGenericStruct3: SomeGenericStruct<SomeType> = SomeGenericStruct<SomeClass>() as SomeGenericStruct<SomeType> // still no work

1 个答案:

答案 0 :(得分:7)

您可以使用泛型方法:

func take<T where T: SomeType>(someType: SomeGenericStruct<T>) { }

唯一的问题是你无法将SomeGenericStruct<SomeType>传递给它。它必须是某种具体类型的通用。如果完全有必要,你可以只有两个函数基本上做同样的事情:

func take(someInput: SomeGenericStruct<SomeType>) { /* do stuff */ }
func take<T where T: SomeType>(someType: SomeGenericStruct<T>) { /* do same stuff */ }