在 Objective-C 中创建有序字符串值集的有效方法
我想以某种方式创建一组类似枚举的字符串,该方式还使我能够按序号值而不是按字母值对它们进行排序。例如:
"Extremely Low" = 0
"Very Low" = 1
"Low" = 2
"Medium = 3
"High" = 4
等等。
我知道在 Java 和 C# 中,枚举类型除了它们的序数值
有什么方法可以在 Objective-C 中实现相同的目标吗
?
I want to create an enum-like set of strings in a way that will also provide me the ability to order them by their ordinal value and NOT by alphabetic value. for example:
"Extremely Low" = 0
"Very Low" = 1
"Low" = 2
"Medium = 3
"High" = 4
and so on.
I know that in Java and C# for example, enum types can have a value besides their ordinal value.
Is there any way to achieve the same goal in Objective-C?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不知道直接的方法来做到这一点。但是,您可以像这样定义 Obj-C 类:
除了使用 switch 之外,这可以完成这项工作。我时常使用类似的类型为用户声明一些“枚举”,因为此类实例的列表可以绑定到 NSArrayController 并在 UI 中使用。
I don't know a direct way to do that. However, you can define an Obj-C class like this:
Except working with the switch this can do the job. I use similar types from time to time to declare some "enums" for the user since a list of such instances can be binded to an NSArrayController and used in the UI.
只需保留 I/O 字符串并使用枚举进行所有计算。例如,定义您的枚举:
您可以在
switch
语句等中使用此枚举。现在您可以使用NSArray
或只是一个简单的 C 数组来从枚举文字映射到字符串:从字符串版本到枚举涉及更多,您可以使用相同的RatingToString数组并进行适当的比较(可能不区分大小写,模糊等)。您还可以使用
NSDictionary
:现在,查找将对您的字符串进行精确匹配,并返回包装为
NSNumber
的Rating
。Just keep the strings for I/O and use an enum for all your computations. For example, define your enum:
You can use this enum in
switch
statements etc. Now you can use anNSArray
or just a simple C-array to map from enum literals to strings:Going from the string version to the enum is more involved, you can use the same
RatingToString
array and do appropriate comparisons (case-insensitive maybe, fuzzy etc.). You could also use anNSDictionary
:Now a lookup will do an exact match on your string and return a
Rating
wrapped as anNSNumber
.您可以使用 Gobra 建议的类或 c 结构数组:
然后您可以执行以下操作:
You can use a class like Gobra suggested or an array of c structs:
then you can do something like this: