2016-05-26 27 views
3

在斯威夫特,還有用來解開自選共同if let模式:如何在Swift模式匹配元組時解開一個Optional?

if let value = optional { 
    print("value is now unwrapped: \(value)") 
} 

目前,我正在做這種模式匹配的,但在一個開關的情況下元組,其中兩個PARAMS是選配:

//url is optional here 
switch (year, url) { 
    case (1990...2015, let unwrappedUrl): 
     print("Current year is \(year), go to: \(unwrappedUrl)") 
}  

然而,這種打印:

"Current year is 2000, go to Optional(www.google.com)" 

有沒有一種方法,我可以解開我的,只有當它是可選的模式匹配不是零?目前,我的解決方法是這樣的:

switch (year, url) { 
    case (1990...2015, let unwrappedUrl) where unwrappedUrl != nil: 
     print("Current year is \(year), go to: \(unwrappedUrl!)") 
}  

回答

8

可以使用x?模式:

case (1990...2015, let unwrappedUrl?): 
    print("Current year is \(year), go to: \(unwrappedUrl)") 

x?是j UST爲.some(x)一個快捷方式,所以這相當於

case (1990...2015, let .some(unwrappedUrl)): 
    print("Current year is \(year), go to: \(unwrappedUrl)") 
0

,你可以這樣做:

switch(year, x) { 
    case (1990...2015,.Some): 
    print("Current year is \(year), go to: \(x!)") 
} 

,你也可以做

switch(year, x) { 
    case (1990...2015, let .Some(unwrappedUrl)): 
    print("Current year is \(year), go to: \(unwrappedUrl)") 
} 
+0

在這個例子中,它的工作原理,但我實際上並沒有想用一個明確的展開操作,因爲我將使用該變量不止一次。有沒有辦法把它打包成另一個變量? –

+0

然後你可以像 案例(1990 ... 2015,let .Some(unwrappedUrl)): @Martin R做過。 – Sahil