加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:00:54 所属栏目:百科 来源:网络整理
导读:我想检查泛型类类型是否为数组: func testT() - WrapperT { let isArray = T.self is ArrayAny ... } 但它警告说 Cast from ‘T.type’ to unrelated type ‘Array’ always fails 我怎么解决这个问题? 补充:我已将我的代码上传到Gist. https://gist.gith
我想检查泛型类类型是否为数组:

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 array
test([1: 2,3: 4]) // The argument is not an array
test((1,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,3])) // The argument is an array of ["_SwiftTypePreservingNSNumber": _SwiftTypePreservingNSNumber]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读