Swift pattern matching with enum and Optional tuple associated values -


i'm using alamofire , use enum describe api used advised in readme.

the endpoints represented 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 mutually exclusive:

 public var urlrequest: nsmutableurlrequest {          let result:(path:string, parameters:[string:anyobject]?) = {             switch self {             case .getstops(let stopcode) 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, _, _) departurecode != nil:                 return ("getnextdepartures", ["stopcode" : stopcode, "departurecode": departurecode!])             case .getnextdepartures(let stopcode, _, let linescode, _) linescode != nil:                 return ("getnextdepartures", ["stopcode" : stopcode, "linescode": linescode!])             case .getnextdepartures(let stopcode, _, _, let destinationscode) destinationscode != nil:                 return ("getnextdepartures", ["stopcode" : stopcode, "destinationscode": destinationscode!])             case .getnextdepartures(let stopcode,_,_,_):                 return ("getnextdepartures",["stopcode":stopcode])             }             }() 

is there way unwrap automatically optional contained (like if let) within tuple , avoiding explicity unwrap in statement :

case .getstops(let stopcode) stopcode != nil :                     return ("getstops.json", ["stopcode" : stopcode!]) 

you can use .some(x) pattern (.some(x) in swift 3):

case .getstops(let .some(stopcode)):      return ("getstops.json", ["stopcode" : stopcode]) 

as of swift 2 (xcode 7), can shorter written x? pattern:

case .getstops(let stopcode?):      return ("getstops.json", ["stopcode" : stopcode]) 

the associated value tested non-nil , unwrapped (similar in optional binding).


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -