2014-10-19 57 views
2

如果想分配一个字符串并检查它在Swift中不是空的。如何使用,如果让与另一个声明在迅速?

if let alternative3Text = attributes.stringForKey("choiceThree") && alternative3Text != "" { 
    // do stuff with alternative3Text 
} 

这是可能的在Swift,或者我必须做一个嵌套的if语句吗?

+0

不,这是不可能的,alternative3Text才可见,如果体内{} – 2014-10-19 18:30:57

回答

7

更新:随着斯威夫特3(Xcode中8)的,额外的条款是 由逗号分隔,不受where

if let alternative3Text = attributes.string(forKey: "choiceThree"), 
     alternative3Text != "" { 
    // do stuff with alternative3Text 
} 

更新:作为雨燕1.2(6.3 Xcode的测试版),你可以结合可选 具有约束力的附加条件:

if let alternative3Text = attributes.stringForKey("choiceThree") where alternative3Text != "" { 
    // do stuff with alternative3Text 
} 

使用开关的情况下仍然有效,但不再是必需的用于这一目的。


老答案: 这是不可能与if声明,但switch。 开关盒可以使用where子句检查附加条件 (documentation)。

假设(从你的问题)是attributes.stringForKey("choiceThree")回报 String?,下面将工作:

switch (attributes.stringForKey("choiceThree")) { 
case .Some(let alternative3Text) where alternative3Text != "": 
    // alternative3Text is the unwrapped String here 
default: 
    break 
} 
+0

凉,不知道开关where条款 - ...但他会有一个如果让和一个开关,所以样本不帮他AFAIK!? – 2014-10-19 21:12:56

+0

@ Daij-Djan:我不确定我是否理解你的问题。 'case。有些(让alternative3Text)'做可选的绑定(通过模式匹配),*代替'if let'。 – 2014-10-19 21:27:33

+0

啊!我只是没有得到它:)谢谢,现在它更凉爽;) – 2014-10-19 21:28:59

0

不,你不能要求额外的表达式在if语句中为真。您将需要添加额外的代码,以您已经提到的嵌套if语句的形式或以其他方式添加代码。如果你唯一的要求是保持这个语句看起来很干净,并且不介意在其他地方移动一些逻辑,你总是可以对你的属性变量进行扩展,以增加这个功能。

下面是一个例子,如果属性是NSUserDefaults的一个实例。 (只是因为它已经包含了stringForKey()实例方法。)

extension NSUserDefaults { 
    func nonEmptyStringForKey(key: String) -> String? { 
     let full = self.stringForKey(key) 

     return full != "" ? full : nil 
    } 
} 

,然后用它像这样

if let alternative3Text = attributes.nonEmptyStringForKey("choiceThree") { 
    // stuff 
}