swift – 具有约束的泛型类型的关联值的枚举案例
发布时间:2020-12-14 04:33:42 所属栏目:百科 来源:网络整理
导读:有没有办法,使用泛型和类型约束,将此枚举的前两个案例合并为一个? enum AllowedValueRange { // Associated value represents (min,max). 'nil' represents // "no limit" for that interval end (+/- infinity) case IntegerRange(Int?,Int?) // Associate
有没有办法,使用泛型和类型约束,将此枚举的前两个案例合并为一个?
enum AllowedValueRange { // Associated value represents (min,max). 'nil' represents // "no limit" for that interval end (+/- infinity) case IntegerRange(Int?,Int?) // Associated value represents (min,max). 'nil' represents // "no limit" for that interval end (+/- infinity) case FloatRange(Float?,Float?) // A finite set of specific values of any type case ArbitrarySet([Any]) // (...Other cases with different structure of associated values // or no associated values...) } 附录: 编辑:事实证明Comparable包含Equatable(?),所以也许我可以这样做: enum AllowedValueRange { // Associated value represents (min,max). 'nil' represents // "no limit" for that interval end (+/- infinity) case NumericRange((min:Comparable?,max:Comparable?)) // (rest omitted) (还切换了一对关联值与单个,名为两个值的元组) 解决方法
你可以定义
enum AllowedValueRange { case NumericRange((min:Comparable?,max:Comparable?)) } 但这样可以让你用两个实例化一个值 let range = AllowedValueRange.NumericRange((min: 12,max: "foo")) 这可能不是你想要的.所以你需要一个通用类型 enum AllowedValueRange<T: Comparable> { case NumericRange((min:T?,max:T?)) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |