everlof everlof - 2 months ago 4x
Swift Question

Pattern match if not nil

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

Can I then use pattern matching to both get the values and unwrap it using pattern matching?

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

Any suggestions?


You can use if with pattern matching and the optional pattern x?:

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