我创建了一个传入的泛型函数,一个特定类型,另一个“泛型”类型。
func initializeCategory<T: UIView> (category: Category, type: T) {
//Find which type 'type' is
//If type is of type, 'UIView' -> do something
//else if type is of type, 'Category' or another type -> Do something else
}
我想做的是找到在我的函数中作为通用类型传入的类型?
是否有更好的方法来创建可以查询传递给它的不同类型的泛型函数?
还是应该像这样<T: Any>
设置它?
P.S类别是UIView的子类
谢谢
更新
基本上,我要完成的工作是通用约束函数。
这里是约束:
view.addSubview(categoryOne)
categoryOne.delegate = self
categoryOne.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16).isActive = true
categoryOne.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true
categoryOne.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true
categoryOne.heightConstraint = categoryOne.heightAnchor.constraint(equalToConstant: 40)
categoryOne.heightConstraint?.isActive = true
我需要的是能够更改“顶部锚”约束的功能。因此,如果我输入UIView的类型,它将被设置为is = constraint(equalTo: view.safeAreaLayoutGuide.topAnchor
等
但是,如果我传入Category的类型(UIView的子类),那么我需要更改约束(equalTo:category.bottomAnchor等
-我以为如果有一个通用函数可以查询传入的类型,我可以得到结果。
答案 0 :(得分:0)
请勿使用type
作为参数,因为它是关键字。以下代码有效。
func initializeCategory<T: UIView> (category: Category, type1: T) {
let a = type(of :type1)
print(a)
}
or
switch type1 {
case is SKView:
print(1)
default:
print(2)
}
答案 1 :(得分:0)
已解决
func initializeCategory (category: Category, type: UIView) {
view.addSubview(category)
category.delegate = self
if type == view {
category.topAnchor.constraint(equalTo: type.safeAreaLayoutGuide.topAnchor, constant: 16).isActive = true
} else {
category.topAnchor.constraint(equalTo: type.bottomAnchor, constant: 16).isActive = true
}
category.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true
category.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true
category.heightConstraint = category.heightAnchor.constraint(equalToConstant: 40)
category.heightConstraint?.isActive = true
}