与enum和可选元组关联值的Swift模式匹配

时间:2015-09-30 06:52:47

标签: swift enums pattern-matching optional

我目前正在使用Alamofire,并使用枚举来描述我在自述文件中建议使用的API。

端点表示如下:

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

可选参数是互斥的:

 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])
            }
            }()

有没有办法在元组中自动解包包含的可选项(如if let),并避免像在此语句中那样明确解包:

case .GetStops(let stopCode) where stopCode != nil :
                    return ("GetStops.json", ["stopCode" : stopCode!])

1 个答案:

答案 0 :(得分:8)

您可以使用.Some(x)模式(Swift 3中的.some(x)):

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

从Swift 2(Xcode 7)开始,这可以缩短为x?模式:

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

关联值被测试为非零和展开(类似于可选绑定)。