我目前正在尝试检查一个对象是不是两类。 在Objective-C中,我会这样做:
if (![vc isKindOfClass:class1] && ![vc isKindOfClass:class2]) { // Do some work }在Swift中,我最终得到了这样的代码:
var isClass1 = false var isClass2 = false if let _ = self.window!.rootViewController as? Class1 { isClass1 = true } if let _ = self.window!.rootViewController as? Class2 { isClass2 = true } if (!isClass1 && !isClass2) { // Do some work }这看起来像我的代码太多了。 这是迅速尝试快速发展的结果。 有没有办法反转as? 并以某种方式链接这两个语句,就像我在obj-C中做的那样? 看到解决这个问题的更短,更高级的方法是非常好的,因为这不可能是正确的解决方案:D。
I am currently trying to check if an object is not kind of two classes. In Objective-C I would do it like that:
if (![vc isKindOfClass:class1] && ![vc isKindOfClass:class2]) { // Do some work }In Swift I ended up with Code like this:
var isClass1 = false var isClass2 = false if let _ = self.window!.rootViewController as? Class1 { isClass1 = true } if let _ = self.window!.rootViewController as? Class2 { isClass2 = true } if (!isClass1 && !isClass2) { // Do some work }This looks like too much code for me. This is the result of swift noob trying to develop in swift. Is there a way to invert the as? and chain both statements somehow like I did in obj-C? It would be really nice to see a shorter and more advanced approach of solving this issue because this can't be the right solution :D.
最满意答案
您可以使用is运算符:
if !(vc is Class1) && !(vc is Class2) { // do some work }或者,更好的(还有更多的Swift-ish),你可以在你的方法开始时使用guard :
guard !(vc is Class1 || vc is Class2) else { return } // do some workguard条件与来自if的guard条件相同,我只将它分组为只有一个否定。
guard是验证输入的首选方法,因为守护程序通常放置在函数的开头,编译器强制您从else分支上的函数返回,这减少了您忘记返回的机会,并且方法体不管输入数据的有效性。
You can use the is operator:
if !(vc is Class1) && !(vc is Class2) { // do some work }Or, better (and more Swift-ish), you can use guard at the beginning of your method:
guard !(vc is Class1 || vc is Class2) else { return } // do some workThe guard condition is the same as the one from if, I only grouped it to have only one negation.
guard is the preferred method of validating inputs, as usually guards are placed at the beginning of the function, and the compiler forces you to return from the function on the else branch, this reduces the chance you forgot to return and the method body executes regardless the validity of the input data.
更多推荐
发布评论