2015-12-22 52 views
2

随着选配,你可以很容易地检查的结果,要么使用非零或传递一个零,用一条线:斯威夫特:在枚举开关没有switch语句

guard x = couldReturnNil() else { return nil } 
// After here, x can be used safely. Calling function 
// can do the same, so nil gets passed back down the calling stack. 

这使得返回式错误操作简单。我想要的是其他枚举类似的一行。就像.Fail/.Succeed的经典例子。例如:

enum Result { 
    .Fail(String)  // Error message. 
    .Succeed(MyType) // Something to work with. 
} 

guard let x = couldFail() case .Succeed(let y) else { return x } 
// Use y safely here. 

现在,这可以在一个笨重的方式来完成,像这样:

let x = couldFail() 
let y:MyType 
switch x { 
case .Succeed(let dummy) { y = dummy } 
case .Fail: return x 
} 

我曾与一个开关之外case语句模式匹配的各种方式左右摆弄,但无济于事。可以使用异常,但肯定是枚举关联值的意图之一是启用这样的东西。也许是自定义运营商也许一些SmartPerson™有一个建议。

回答

3

像这样的东西? guard/case与模式匹配:

let x = couldFail() 
guard case let .Succeed(y) = x else { return x } 
// y can safely be used here ... 

如果x需要在其他体,那么你必须给它一个变量首先分配给 。否则,单线程会做:

guard case let .Succeed(y) = couldFail() else { return } 
// y can safely be used here ... 
+0

是的,我试图将你的两个陈述塞进一个。但这可能是我们能做的最好的事情。尽管如此,这是一个巨大的改进方式。 –

+0

@AndrewDuncan:在警戒条件下声明的变量在主体中不可用,所以这是我能找到的最好的。 –