swift - 如何检查泛型类类型是数组?

标签 swift swift3

我想检查泛型类类型是否是数组:

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, 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]

关于swift - 如何检查泛型类类型是数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41518371/

相关文章:

swift - 在 Swift 4 中创建简单的日期倒计时应用程序时出错

ios - 是否有类似 dump() 的函数返回一个字符串?

arrays - joined() 还是 flatMap(_ :) perform better in Swift 3?

ios - 如何使用 Swift 3 打电话?

ios - 如何覆盖 swift3 中的高分

iphone - 在 Swift 中将数据从 Apple Watch 传输到 iPhone

ios - 当应用程序处于后台时调用 URLSession.shared.dataTask

ios - 在 swift 中使用 JSONSerialization 和 JSONDecoder 有什么区别?

ios - 如何在 Swift 中创建自动完成文本字段

ios - IPA 文件结构 - SupportSwift & Symbols