模式匹配,如果不是零

时间:2016-08-18 12:05:19

标签: swift

# 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)
}

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

您可以使用if模式匹配和可选模式 x?

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

答案 1 :(得分:1)

与上述类似,但不同......

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