Chaining methods in swift — (Don’t confuse with optional chaining)

Last day, when I was doing the api calls using almofire, I came across a weird looking method call which was something like creating an object of almofire and then calling a method with the object created ,followed by another method after a dot(.), followed by another method so far and so on…

class Celsius {var temperatureInCelsius: Doubleinit(fromFahrenheit fahrenheit: Double) {temperatureInCelsius = (fahrenheit — 32.0) / 1.8}init(fromKelvin kelvin: Double) {temperatureInCelsius = kelvin — 273.15}func printTemperature() {print(“Temperature is \(temperatureInCelsius)”)}}
Celsius(fromKelvin: 400).printTemperature() 
// prints Temperature is 126.85

Chaining methods example:

Let’s create an APICaller class.

let params = [“key1”:”value1",”key2":”value2"]APICaller().urlString(“www.google.com").method(.post).parameters(params).response { (resultDict) inprint(resultDict[“result”]!)}//----------------
// prints the following in console.
("Result values1","Result values2","Result values3","Result values4")
  1. Create an instance of APICaller class.
  2. Call urlString method with a string as parameter. This will set the url property in APICaller class and return self .
  3. Call method method which set the method property of APICaller class and return self .
  4. Call parameters method which sets the parameters for the api call and return self .
  5. Finally, call the method called response which has a trailing closure as parameter. Here, do the API call stuff and on success or failure, call the callback closure with the result object. Here the closure takes only a dictionary of type Dictionary<String,AnyObject>.

If you enjoyed reading this post, please share and recommend it so others can find it 💚💚💚💚💚💚 !!!!

--

--

iOS and tvOS developer, dreamer, photographer 🤨

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store