簡體   English   中英

如何檢查泛型類類型是數組?

[英]How to check generic class type is array?

我想檢查泛型類類型是否為數組:

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

但它警告說

從'T.type'轉換為不相關的類型'Array'總是失敗

我怎么解決這個問題?

補充:我已將我的代碼上傳到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]

你沒有傳遞任何參數,所以沒有類型和泛型函數沒有意義。 刪除泛型類型:

func() {}

或者,如果你想傳遞一個參數:

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

test(argument: array)

印刷品: true

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM