2016-08-18 86 views
2
# Let's say I've got the following typealias 
public typealias DateRange = (from: NSDate?, to: NSDate?) 

# And use it here 
var selectedDateRange: DateRange = (nil, nil) 

然後我可以使用模式匹配來獲取值並使用模式匹配將其解包嗎?模式匹配如果不爲零

# I can check vs. `nil` like so: 

if case (nil, nil) = segmentControl.selectedCustomDateRange { 
    print("Damn, nil!") 
} 

# And I want something shorter than 
if let from = segmentControl.selectedDateRange.from, 
    let to = segmentControl.selectedDateRange.to 
{ 
    model.setPeriod(from, to: to) 
} 

有什麼建議嗎?

回答

3

可以使用if與模式匹配和可選的模式 x?

if case let (from?, to?) = selectedDateRange { 
    model.setPeriod(from, to: to) 
} 
+0

啊!謝謝。我確實嘗試過變體,比如'(從:NSDate ?,到:NSDate?)',但那不起作用。 – netigger

1

以上,但不同的類似......

guard case let (from?, to?) = selectedDateRange else { 
    print("Damn, at least one nil!") 
    return 
} 
model.setPeriod(from, to: to)} 
+0

謝謝你。不同的情況需要不同的解決方案,有時候警衛是首選。 – netigger