如何获得一个快速枚举的相关值,而不考虑枚举大小写 [英] How to get a swift enum's associated value regardless of the enum case
问题描述
我有一个对象FormField有两个属性:a < value
类型 - 因此我已经使它任何!
。不过,我在另一个问题中被告知要使用枚举与相关值而不是任何!
。
枚举值{
case Text(String!)
case CoreDataObject(NSManagedObject!)
}
类FormField {
var name:String
var value:值?
// initializers ...
}
以检查无效。如果我想为窗体中所有缺少的字段显示一个警报视图,则我必须对switch语句中的每个案例重复一次检查:
<$ p $对于self.fields中的字段,p>
{
如果let value = field.value {
切换值{
case .Text(let text):
if text == nil {
missingFields.append(field.name)
}
case .CoreDataObject(let object):
if object == nil {
missingFields .append(field.name)
}
}
}
}
b $ b
是否有更短的方式访问枚举的关联值,而不管类型?如果我使FormField.value为 Any!
,上面的代码将很容易:
for self.fields {
if field.value == nil {
missingFields.append(field.name)
}
}
定义方法 isMissing c $ c>里面的
枚举
- 写一次,只有一次。那么你几乎可以得到你喜欢的:
for self.fields {
if field.value.isMissing (){
missingFields.append(field.name)
}
}
$ b b
它看起来像这样(来自Swift解释器):
1> class Foo {}
>
2>枚举值{
3. case一(Foo!)
4. case二(Foo!)
5.
6. func isMissing() - > Bool {
7. switch self {
8. case let .One(foo):return foo == nil
9. case let .Two(foo):return foo == nil
10.}
11.}
12.}
13> let aVal = Value.One(nil)
aVal:Value = One {
One = nil
}
14> aVal.isMissing()
$ R0:Bool = true
I have an object FormField which has two properties: a String name
, and a value
which can accept any type--hence I've made it Any!
. However, I've been told in a separate question to use an enum with associated values instead of Any!
.
enum Value {
case Text(String!)
case CoreDataObject(NSManagedObject!)
}
class FormField {
var name: String
var value: Value?
// initializers...
}
This approach makes it awfully verbose to check for nullity however. If I wanted to display an alert view for all the missing fields in the form, I'll have to repeat a nil check for every case in a switch statement:
for field in self.fields {
if let value = field.value {
switch value {
case .Text(let text):
if text == nil {
missingFields.append(field.name)
}
case .CoreDataObject(let object):
if object == nil {
missingFields.append(field.name)
}
}
}
}
Is there a shorter way of accessing the enum's associated value, regardless of the type? If I make FormField.value an Any!
the above code would be as easy as:
for field in self.fields {
if field.value == nil {
missingFields.append(field.name)
}
}
Define a method isMissing()
inside the enum
- write it once and only once. Then you get nearly exactly what you prefer:
for field in self.fields {
if field.value.isMissing() {
missingFields.append(field.name)
}
}
It would look something like this (from the Swift Interpreter):
1> class Foo {}
>
2> enum Value {
3. case One(Foo!)
4. case Two(Foo!)
5.
6. func isMissing () -> Bool {
7. switch self {
8. case let .One(foo): return foo == nil
9. case let .Two(foo): return foo == nil
10. }
11. }
12. }
13> let aVal = Value.One(nil)
aVal: Value = One {
One = nil
}
14> aVal.isMissing()
$R0: Bool = true
这篇关于如何获得一个快速枚举的相关值,而不考虑枚举大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!