2017-01-07 22 views
6

Ben genel sınıf türü bir Array olup olmadığını kontrol etmek istiyorum:Genel sınıf türü nasıl kontrol edilir?

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

Ama ilgisiz türüne 'T.type' 'Dizi' den

Cast uyarıyor hep

başarısız

Bu sorunu nasıl çözebilirim?

eklendi: Kodları Gist'e yükledim. https://gist.github.com/nallwhy/6dca541a2d1d468e0be03c97add384de

Yapmak istediğim, json yanıtını bir dizi modele veya yalnızca bir modele göre ayrıştırmaktır.

+0

İlgili: [Nasıl bir nesne bir koleksiyon olup olmadığını kontrol edersiniz? (Swift)] (http://stackoverflow.com/q/41236021/2976878) – Hamish

cevap

2

, sen Any kullanabilirsiniz bir argüman geçirmek istiyorsanız,

func() {} 

ya: Ya genel tür kaldırın. Mirror ile birleştirin ve, örneğin, böyle bir şey yapabileceğini:

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

Herhangi bir bağımsız değişken iletmiyorsunuz, bu nedenle hiçbir tür yok ve genel bir işlev anlamlı değil.

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

test(argument: array) 

Baskılar: yorumcu @Holex söylediği gibi true

+0

@shallowThrought Örnek kodu değiştirdim. – mayTree

+1

@mayTree hala bir argümanınız yok, yani bir tür geçirmiyorsunuz. 'T' türü nasıl bulunmalıdır? Yöntemin 'T' olarak geri dönmesini bekliyorsunuz? – shallowThought

+0

Bunun için neden _generics_'a ihtiyacınız var? Basit bir 'Any' da işi yapabilir - kim 'true' değerini döndürür? çünkü bu sizin yönteminiz değil. – holex

İlgili konular