本文介绍了在swift中获取泛型的参数化类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在swift中获得泛型的参数化类型?例如,检查类型的大小。

解决方案

例如,当您有 Array< ; Int> value,你想要的是 Int type。



我相信是没有通用的方式来做到这一点。



某些类型具有 typealias ed通用参数,您可以通过那个名字。例如:

  let array:Array< UInt16> = [1,2,3] 
let elementType = array.dynamicType.Element.self // - > Swift.UInt16
sizeof(elementType)// - > 2

这是因为 Array typealiased Element = T

  struct Array< T> :MutableCollectionType,Sliceable,_DestructorSafeContainer {

///这个`Array`存储的元素的类型
typealias Element = T
typealias ,你可以通过扩展名添加它



/ code>:

 扩展非托管{
typealias Payload = T
}

让某些东西:非托管< NSString> = .passRetained(test)
something.dynamicType.Payload.self // - > NSString


How can I get the parameterised type of a generic in swift? For example to check the sizeof the type.

解决方案

I suppose, for example, when you have Array<Int> value, what you want is Int type.

I believe there is no generic way to do that.

Some type has typealiased the generic parameter, you can get it with that name. For example:

let array: Array<UInt16> = [1,2,3]
let elementType = array.dynamicType.Element.self // -> Swift.UInt16
sizeof(elementType) // -> 2

This works because Array typealiased Element = T:

struct Array<T> : MutableCollectionType, Sliceable, _DestructorSafeContainer {

    /// The type of element stored by this `Array`
    typealias Element = T

Even if it does not have the typealias, you can add it by extension:

extension Unmanaged {
    typealias Payload = T
}

let something: Unmanaged<NSString> = .passRetained("test")
something.dynamicType.Payload.self // -> NSString

这篇关于在swift中获取泛型的参数化类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:42