Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift pattern matching with enum and Optional tuple associated values

I'm currently using Alamofire and I use an enum to describe the API I used as advised in the readme.

The endpoints are represented as follows:

public enum API {
    case GetStops(stopCode:String?)
    case GetPhysicalStops
    case GetLinesColors
    case GetNextDepartures(stopCode:String, departureCode:String?, linesCode:String?, destinationsCode:String?)
}

The optional parameters are mutually exclusive:

 public var URLRequest: NSMutableURLRequest {

        let result:(path:String, parameters:[String:AnyObject]?) = {
            switch self {
            case .GetStops(let stopCode) where stopCode != nil :
                return ("GetStops.json", ["stopCode" : stopCode!])
            case .GetStops(_):
                return ("GetStops.json", nil)
            case .GetPhysicalStops:
                 return ("GetPhysicalStops.json", nil)
            case .GetLinesColors:
                return ("GetLinesColors",nil)
            case .GetNextDepartures(let stopCode, let departureCode, _, _) where departureCode != nil:
                return ("GetNextDepartures", ["stopCode" : stopCode, "departureCode": departureCode!])
            case .GetNextDepartures(let stopCode, _, let linesCode, _) where linesCode != nil:
                return ("GetNextDepartures", ["stopCode" : stopCode, "linesCode": linesCode!])
            case .GetNextDepartures(let stopCode, _, _, let destinationsCode) where destinationsCode != nil:
                return ("GetNextDepartures", ["stopCode" : stopCode, "destinationsCode": destinationsCode!])
            case .GetNextDepartures(let stopCode,_,_,_):
                return ("GetNextDepartures",["stopCode":stopCode])
            }
            }()

Is there a way to unwrap automatically the optional contained (like if let) within the tuple and avoiding to explicity unwrap like in this statement :

case .GetStops(let stopCode) where stopCode != nil :
                    return ("GetStops.json", ["stopCode" : stopCode!])
like image 772
yageek Avatar asked Dec 18 '22 23:12

yageek


1 Answers

You can use the .Some(x) pattern (.some(x) in Swift 3):

case .GetStops(let .Some(stopCode)):
     return ("GetStops.json", ["stopCode" : stopCode])

As of Swift 2 (Xcode 7), this can be shorter written as x? pattern:

case .GetStops(let stopCode?):
     return ("GetStops.json", ["stopCode" : stopCode])

The associated value is tested to be non-nil and unwrapped (similar as in an optional binding).

like image 197
Martin R Avatar answered Dec 26 '22 00:12

Martin R