everlof everlof - 1 year ago 107
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?

Answer Source

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

if case let (from?, to?) = selectedDateRange {
    model.setPeriod(from, to: to)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download