func test<T>() -> Wrapper<T> { let isArray = T.self is Array<Any> ... }
但它警告说
Cast from ‘T.type’ to unrelated type ‘Array’ always fails
我怎么解决这个问题?
补充:我已将我的代码上传到Gist.
https://gist.github.com/nallwhy/6dca541a2d1d468e0be03c97add384de
我想要做的是根据它是一个模型数组或只是一个模型来解析Json响应.
解决方法 正如评论员@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,"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 arraytest([1: 2,3: 4]) // The argument is not an arraytest((1,3)) // The argument is not an arraytest(3) // The argument is not an arraytest("3") // The argument is not an arraytest(NSObject()) // The argument is not an arraytest(NSArray(array:[1,3])) // The argument is an array of ["_SwiftTypePreservingNSNumber": _SwiftTypePreservingNSNumber]总结
以上是内存溢出为你收集整理的swift – 如何检查泛型类类型是数组?全部内容,希望文章能够帮你解决swift – 如何检查泛型类类型是数组?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)