Before we begin diving into the nitty-gritty of the code, we begin by defining a few enum types that will make it much more convenient to connect to each of the API endpoints as well as to interpret the server's response to our API request.

First, we define an OxfordHTTPStatusCode enum type, whose underlying value is an integer correspdoning to the status code of the HTTP response:



enum OxfordHTTPStatusCode: Int{

     case Success =  200
     case BadRequest =  400
     case AuthenticationFailed =  403
     case NotFound =  404
     case InternalServerError =  500
     case BadGateway =  502
     case ServiceUnavailable =  503
     case GatewayTimeout =  504
     case OtherStatusCode 
    
     func  statusCodeMessage() -> String{
         switch  self {
        case  .AuthenticationFailed:
            return "The request failed due to invalid credentials.Please check that the app_id and app_key are correct, and that the URL you are trying to access is correct. These can be found in the API Credentials page"
        case .BadGateway:
            return  "Oxford Dictionaries API is down or being upgraded."
        case .BadRequest:
            return "The request was invalid or cannot be otherwise served. An accompanying error message will explain further.For example, when the filters provided are unknown, the source and target languages in the translation endpoint are the same, or a numeric parameter such as offset and limit in the wordlist endpoint cannot be evaluated as a number."
        case .GatewayTimeout:
            return "The Oxford Dictionaries API servers are up, but the request couldn’t be serviced due to some failure within our stack. Please try again later."
        case .InternalServerError:
            return "Something is broken. Please contact us so the Oxford Dictionaries API team can investigate."
        case .NotFound:
            return "No information available or the requested URL was not found on the server.For example, when the headword could not be found, a region or domain identifier do not exist, or the headword does not contain any attribute that match the filters in the request. It may also be the case that the URL is misspelled or incomplete."
        case .ServiceUnavailable:
            return "The Oxford Dictionaries API servers are up, but overloaded with requests. Please try again later."
        case .Success:
            return "Success!"
        case .OtherStatusCode:
            return "Unknown http status code received"
        default:
            return "Unknown http status code received"
        }
    }
    
}

		
	

The enum type also include a function for getting specific status code messages based on the particular status code obtained. This will be useful later for debugging, since we will want to understand what exactly the status code means when we test our API client using API requests with different urls and headers.

In addition, we will define enums that will be helpful for specifying different values for the different optional filter parameters that can be included in the url string. This will be helpful in constructing url strings for our API requests. The goal of this API client is to make the publicly-accessible methods for connecting to the API as friendly as possible while hiding all the nitty-gritty details of the implementation.

To that end, we will define additional types as follow: OxfordAPILanguage, OxfordRegion, OxfordDomain, OxfordLanguageRegister, OxfordLexicalCategory and OxfordLexicalFeature


enum OxfordAPILanguage: String{
    case English = "en"
    case Spanish = "es"
    case Malay = "ms"
    case Setswana = "tn"
    case Swahili = "sw"
    case NorthernSoho = "nso"
    case Indonesia = "id"
    case Latvian = "lv"
    case Urdu = "ur"
    case Romanian = "ro"
    case Hindi = "hi"
    case German = "de"
    case Portuguese = "pt"
    case Tamil = "ta"
    case Gujarati = "gu"
}

The Oxford dictionary allows you to look up words based on their regiion, namely English words as used in Great Britain (abbreviated gb) or in the United States(abbreviated us). Each enum case is written in the abbreviated form.


enum OxfordRegion: String{
    case gb,us
}

In addition to regions, the API endpoints allow the user to look up words based on a specific domain, that is, a topical area such as archaeology,biology, or carpentry. Since the topical domain is a filter parameter for the wordlist endpoint, the underlying data type is configured as a string.



enum OxfordDomain: String{
    case air_force, alcoholic,american_civil_war,american_football,amerindian
    case anatomy,ancient_history,angling,anthropology, archaeology, archery, architecture
    case art, artefacts, arts_and_humanities, astrology, astronomy
    case athletics, audio, australian_rules, aviation, ballet, baseball, basketball, bellringing
    case biblical, billiards, biochemistry, biology, bird, bookbinding, botany, bowling, bowls,boxing
    case breed, brewing
    case bridge,broadcasting,buddhism,building,bullfighting,camping,canals,cards,carpentry
    case chemistry, chess, christian,church_architecture,civil_engineering,clock_making
    case clothing, coffee,commerce,commercial_fishing,complementary_medicine,computing
    case cooking,cosmetics,cricket,crime,croquet,crystallography,currency,cycling
    case dance,dentistry,drink,dyeing,early_modern_history,ecclesiastical
    case ecology,economics,education,egyptian_history,electoral,electrical,electronics,element
    case english_civil_war,falconry,farming,fashion,fencing,film,finance,fire_service,first_world_war
    case fish, food, forestr,freemasonry,french_revolution,furniture,gambling,games,gaming,genetics
    case geography,geology,geometry,glassmaking,golf,goods_vehicles,grammar,greek_histroy,gymnastics
    case hairdressing,handwriting,heraldry,hinduism,history,hockey,honour,horology,horticulture,hotels
    case hunting,insect,instruments,intelligence,invertebrate,islam,jazz,jewellery
    case journalism,judaism,knitting,language,law,leather,linguistics
    case literature,logic,lower_plant,mammal,marriage,martial_arts
    case mathematics,measure,mechanics,medicine,medieval_histor
     case metallurgy,meteorology,microbiology,military,military_history
     case mineral,mining,motor_racing,motoring,music,mountaineering,musical_direction,mythology
    case napoleonic_wars,narcotics,nautical,naval,needlework,numismatics,occult,oceanography
    case office, oil_industry,optics,palaeontology,parliament,pathology,penal
   case people,pharmaceutics,philately,philosophy,phonetics,photography,physics
    case physiology,plant,plumbing,politics, police,popular_music,postal,potter,printing,professions
    case prosody,psychiatry,psychology,publishing,racing,railways,rank,relationships
    case religion, reptile,restaurants,retail,rhetoric, riding,roads,rock,roman_catholic_church
    case roman_history,rowing,royalty,rugby,savoury,scouting,second_world_war
    case sex,shoemaking,sikhism,skateboarding,skating,skiing,smoking,snowboarding,soccer
    case sociology,space,sport,statistics,stock_exchange,surfing,surgery,surveying,sweet,swimming
    case tea, team_sports,technology,telecommunications,tennis,textiles,theatre,theology,timber,title
      case tools, trade_unionism,transport,university,variety,veterinar,video
    case war_of_american_independence,weapons,weightlifting,wine,wrestling,yoga,zoology


}

The wordlist endpoint also has a filter for language registers, which refers to styles or manners of speaking based on specific literary, social, political, and cultural contexts, such as coarse_slang and literal. The enum is defined below with an underlying string data type so that the enum can be used more conveniently in building the API request url.




enum OxfordLanguageRegister: String{
    case allusive, archaic, allusively, army_slang, black_english
    case coarse_slang, cant, college_slang, concrete, contemptuous
    case dated, depreciative,depreciatively, derogatory, dialect
    case dismissive, disused, emphatically, especially, euphemism
    case euphemistic, figurative, generally, historical, humorous, humorously
    case hyperbolical, hyperbolically, informal, ironic, ironically
    case literal, literary, military_slang, nautical_slang
    case nursery, obsolete, offensive, personified, poetic, police_slang
    case prison_slang, proverb, pseuodo_archaic, rare,rarely,rhyming_slang
    case school_slang,slang, technical, temporary,theatrical_slang
    case trademark, trademark_in_uk, trademark_in_us,transferred
    case university_slang, vulgar_slang
    
}
         


enum OxfordLexicalCategory: String{
    
    case noun, verb
    case combining_form
    case adjective,adverb
    case conjunction, contraction
    case determiner,idiomatic,interjection
    case numeral, particle, other
    case predeterminer, prefix, suffix 
    case preposition,pronoun,residual
    
    
    
    static let allPartsOfSpeech: [String] = [
        .noun, .verb, .combining_form, .adjective, .adverb, .conjunction, .contraction,
        .determiner, .idiomatic, .interjection, .numeral, .particle, .other,
        .predeterminer, .prefix,.suffix,.preposition,.pronoun,.residual
    ]
}

enum OxfordGrammaticalFeature: String{
    
    //mass
    case mass
    
    //collectivity
    case collective
    
    //adjective function
    case attributive
    case predicative
    
    //subcategorization
    case intransitive
    case transitive
    
    //auxiliary
    case auxiliary
    
    //residual
    case abbreviation
    case symbol
    
    case interrogative
    case possessive
    case relative
    
    //person
    case third
    
    //unit structure
    case phrasal
    
    //number
    case singular
    case plural
    
    //numeral
    case cardinal
    case ordinal
    
    //tense
    case past
    case present
    
    //degree
    case comparative
    case positive
    case superlative
    
    //event modality
    case modal
    
    //gender
    case feminine
    
    //moode
    case conditional
    case subjunctive
    
    //non finiteness
    case infinitive
    case past_participle
    case present_participle
    
}


     

As you can see, each of these enums have an underlying string type, which will make it easier to eventually get url query parameters needed to build the string for our url query string. In the case of the language enum, the full name of the language is used for the case values, while the actually language abbreviation codes are used for the underlying string values. Using enums in this way makes it easier to take advantage of Xcode's autocomplete feature as well as to avoid stringly-typed errors that easily occur and can also be hard to detect when construct our query strings later on.

To continue, please click here

If you feel confused or are having trouble following, you can go back to the previous page or back to the table of contents table of contents.