2017-01-07 59 views
6

我要检查泛型类的类型是否为数组:如何检查泛型类型是数组?

func test<T>() -> Wrapper<T> { 
    let isArray = T.self is Array<Any> 
    ... 
} 

但它从“T.type”无关型“数组”警告

演员总是失败

我该如何解决这个问题?

补充:我已将我的代码上传到Gist。 https://gist.github.com/nallwhy/6dca541a2d1d468e0be03c97add384de

我想要做的就是根据它是一个模型或只是一个模型的数组解析json响应。

+0

相关:如何检查对象是否是一个集合? (Swift)](http://stackoverflow.com/q/41236021/2976878) – Hamish

回答

2

正如评论员@Holex说,你可以使用Any。与Mirror结合起来,你可以,例如,做这样的事情:

func isItACollection(_ any: Any) -> [String : Any.Type]? { 
    let m = Mirror(reflecting: any) 
    switch m.displayStyle { 
    case .some(.collection): 
     print("Collection, \(m.children.count) elements \(m.subjectType)") 
     var types: [String: Any.Type] = [:] 
     for (_, t) in m.children { 
      types["\(type(of: t))"] = type(of: t) 
     } 
     return types 
    default: // Others are .Struct, .Class, .Enum 
     print("Not a collection") 
     return nil 
    } 
} 

func test(_ a: Any) -> String { 
    switch isItACollection(a) { 
    case .some(let X): 
     return "The argument is an array of \(X)" 
    default: 
     return "The argument is not an array" 
    } 
} 

test([1, 2, 3]) // The argument is an array of ["Int": Swift.Int] 
test([1, 2, "3"]) // The argument is an array of ["Int": Swift.Int, "String": Swift.String] 
test(["1", "2", "3"]) // The argument is an array of ["String": Swift.String] 
test(Set<String>()) // The argument is not an array 
test([1: 2, 3: 4]) // The argument is not an array 
test((1, 2, 3)) // The argument is not an array 
test(3) // The argument is not an array 
test("3") // The argument is not an array 
test(NSObject()) // The argument is not an array 
test(NSArray(array:[1, 2, 3])) // The argument is an array of ["_SwiftTypePreservingNSNumber": _SwiftTypePreservingNSNumber] 
-1

您没有传递任何参数,所以没有类型,并且泛型函数没有意义。要么删除泛型类型:

func() {} 

,或者,如果你想传递一个论点:

let array = ["test", "test"] 
func test<T>(argument: T) { 
    let isArray = argument is Array<Any> 
    print(isArray) 
} 

test(argument: array) 

打印:true

+0

@shallowThrought我改变了示例代码。 – mayTree

+1

@mayTree你仍然没有参数,即你没有传递一个类型。应该怎样找出'T'的类型?你希望该方法返回为'T'? – shallowThought

+0

为什么你需要_generics_?一个简单的“任何”都可以完成这项工作 - 谁会返回“真正”的价值?因为它明显不是你的方法。 – holex