2014-09-30 112 views
3

我試圖從變量中請求一些值。 變量都將有天氣的描述,我想,以顯示不同的圖像(如日曬,雨淋或左右),要求特定的詞 的事情是我有這樣的代碼:Swift switch語句匹配字符串的子字符串

if self.descriptionWeather.description.rangeOfString("Clear") != nil 
{ 
    self.imageWeather.image = self.soleadoImage 
} 
if self.descriptionWeather.description.rangeOfString("rain") != nil 
{ 
    self.imageWeather.image = self.soleadoImage 
} 
if self.descriptionWeather.description.rangeOfString("broken clouds") != nil 
{ 
    self.imageWeather.image = self.nubladoImage 
} 

因爲當我試圖添加一個「OR」條件xcode給了我一些奇怪的錯誤。

是否有可能做一個swich句子呢?或者任何人都知道如何添加或條件的if條款?

+4

您是如何添加「OR」條件以及獲得了什麼奇怪錯誤的? – Thilo 2014-09-30 02:15:10

+0

例如,如果我想提出的第一和第二個在同一個if語句:\t \t \t \t \t \t \t如果self.descriptionWeather.description.rangeOfString(「清除」)=零| self.descriptionWeather.description.rangeOfString( 「破雲」)!=零 \t \t \t \t \t \t \t { \t \t \t \t \t \t \t \t self.imageWeather.image = self.soleadoImage \t \t \t \t \t \t \t},錯誤是:非關聯運算符與相同優先級的運算符相鄰,並且不能用類型爲'($ T17,NilLiteralConvert ible)' – LPS 2014-09-30 02:23:21

回答

4

Swift語言有兩種OR運算符 - 位運算符|(單一垂直線),邏輯運算符||(雙垂直線)。在這種情況下,你需要一個邏輯OR

if self.descriptionWeather.description.rangeOfString("Clear") != nil || self.descriptionWeather.description.rangeOfString("clear") != nil { 
    self.imageWeather.image = self.soleadoImage 
} 

與Objective-C的在那裏你可以換取得到一個稍微不同的運行時語義與按位OR脫身,斯威夫特需要表達的邏輯OR以上。

+0

感謝您的回答!現在它工作! – LPS 2014-09-30 02:40:01

8

您可以使用switch語句使用值綁定和where子句執行此操作。但首先將字符串轉換爲小寫!

var desc = "Going to be clear and bright tomorrow" 

switch desc.lowercaseString as NSString { 
case let x where x.rangeOfString("clear").length != 0: 
    println("clear") 
case let x where x.rangeOfString("cloudy").length != 0: 
    println("cloudy") 
default: 
    println("no match") 
} 

// prints "clear" 
+0

謝謝你的回答!我會嘗試 – LPS 2014-09-30 02:41:19

2

這實際上是匹配的情況下,讓您匹配正則表達式中使用switch語句這link還介紹了超載運算符〜=。