Skip to content

Instantly share code, notes, and snippets.

@crazytonyli
Created September 27, 2015 13:14
Show Gist options
  • Save crazytonyli/6b9983d41d667b573018 to your computer and use it in GitHub Desktop.
Save crazytonyli/6b9983d41d667b573018 to your computer and use it in GitHub Desktop.
Get generic type
struct Stack <Element> {
let values: [Element]
var elementType: Any {
get {
return Element.self
}
}
}
let intStack = Stack<Int>(values: [1, 2, 3])
print(intStack.elementType)
let vcStack = Stack<UIViewController>(values:[UIViewController()])
print(vcStack.elementType)
@eyeplum
Copy link

eyeplum commented Sep 27, 2015

另外一种方法可以不通过 Element 找类型:

var elementTypeInContainer: Any {
  get {
    return values.dynamicType.Element.self
  }
}

@crazytonyli
Copy link
Author

@eyeplum 想取的不是 values 的泛型类型,而是 Stack 的泛型类型。可能这个栗子有点歧义……

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment