【问题标题】:How to check generic class type is array?如何检查泛型类类型是数组?
【发布时间】:2017-01-07 06:02:17
【问题描述】:

我要检查泛型类类型是否为数组:

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

但它会发出警告

从“T.type”转换为不相关类型“Array”总是失败

我该如何解决这个问题?

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

我要做的是根据它是一组模型还是一个模型来解析 json 响应。

【问题讨论】:

标签: swift swift3


【解决方案1】:

正如评论员@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]

【讨论】:

    【解决方案2】:

    尝试定义一个数组标记协议。参考this answer。

    protocol AnyTypeOfArray {}
    extension Array: AnyTypeOfArray {}
    extension NSArray: AnyTypeOfArray {}
    
    func isArray<T>(type: T.Type) -> Bool {
        return T.self is AnyTypeOfArray.Type
    }
    
    print(isArray(type: [String].self))   // true
    print(isArray(type: String.self))     // false
    

    【讨论】:

      【解决方案3】:

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

      func() {}
      

      或者,如果你想传递一个参数:

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

      打印:true

      【讨论】:

      • @mayTree 您仍然没有参数,即您没有传递类型。 T的类型应该怎么查?您希望该方法以 T 的形式返回什么?
      • 你为什么需要 generics 呢?一个简单的Any 也可以完成这项工作——谁会返回true 值?因为这绝对不是你的方法。
      • @holex 我只是想保留这个例子。当然不需要泛型。抱歉,将“returns”替换为“prints”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-24
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      相关资源
      最近更新 更多