首页 > 解决方案 > Switch case 语句 - 通用关联类型

问题描述

我正在尝试将泛型类型与 switch case 语句相关联,但出现编译时错误。

enum TextEditEvent{
case editingBegin(UITextField)
case editingEnd(UITextField, UITextField?)
case textChanged<T>(String?, UILabel?, T, String) where T:Object, T:Updatable
}

任何帮助将非常感激。

标签: iosswiftgenericsenums

解决方案


enum本身必须被声明为泛型,而不是它的大小写,并且您不能在case声明中使用 where 子句,您需要在关联值上指定泛型类型约束。

enum TextEditEvent<T>{
    case editingBegin(UITextField)
    case editingEnd(UITextField, UITextField?)
    case textChanged(String?, UILabel?, T:Object, Updateable, String)
}

或者,如果您想T在整体中拥有这些类型约束enum,不仅针对这种textChanged情况,您可以enum这样声明:

enum TextEditEvent<T: Object, Updateable>{
    case editingBegin(UITextField)
    case editingEnd(UITextField, UITextField?)
    case textChanged(String?, UILabel?, T, String)
}

推荐阅读