【问题标题】:Switch case statement - Generic associated typeSwitch case 语句 - 通用关联类型
【发布时间】:2018-05-26 15:58:15
【问题描述】:

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

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

任何帮助将不胜感激。

【问题讨论】:

    标签: ios swift generics enums


    【解决方案1】:

    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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-24
      • 2013-09-24
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 2012-06-18
      相关资源
      最近更新 更多