2/3 Writing scripts in Swift language
First part of this series introduced how scripts can be written in Apple’s Swift programming language while also having referenced a library of our own. sayHello.swift
script was implemented by calling a public field, abc.text
, located in this library.
This second part is showing how a script evolves from writing a few short and dirty lines to a rather complex ensemble of writing functions and calling 3rd party library tools — all under swift-sh
’s umbrella .
The scope of this second script is to write some code that retrieves the price of a cryptocurrency pair, say BTCUSDT
, published by the cryptocurrency exchange Binance
.
The script life-cycle is described in this pull request :
-
First commit introduces the command line arguments that the script is expecting, namely that the cryptocurrency pair like
BTCUSDT
must be specified as the only required input parameter. -
Second commit introduces the 3rd party libraries that the script will be using : Alamofire and SwiftyJSON . Their versions are specified as per the pattern introduced by swift-sh tool:
import Alamofire // @Alamofire ~> 5.2 import SwiftyJSON // @SwiftyJSON ~> 5.0.0
Then it follows a very quick and dirty approach of getting the work done, assuming that everything will work just fine and no errors will ever happen. Running the script first time , without any input parameters, will make
swift-sh
tool fetch the 3rd party libraries then execute the script code; running the script the second time, with the correct input parameterBTCUSDT
will make the script output the expected price for the cryptocurrency pair; finally, running the script with an invalid input parameter such asBTCUSDTX
will make the script output some nasty error — which is expected, considering that the code does not handle any kind of error. Here’s the output of these three runs :What comes next are several steps that would improve the source code sufficiently such that it can be used in a production setting :
-
Third commit introduces the synchronisation via
DispatchGroup
as well as thecURL
debug-like output so we’d know what kind of request is actually being sent to the exchange -
Fourth commit introduces the error handling of the exchange response in case of various scenarios : invalid pair, wrong response etc.
-
Fifth commit replaces the entire logic written thus far with a function with signature :
func getPrice(ofPair pair:String) throws -> (String, Decimal)
It returns the a tuple of (pair,price) upon successful processing or it throws an exception of type Failure in case of an error .
-
Finally, the sixth commit decides to replace
DispatchGroup
withDispatchSemaphore
for better and easier understanding of the source code.
All in all, the script is now doing a rather decent job of retrieving the price of a cryptocurrency pair while also dealing with potential errors that might come to its way :
That’s it for now. Enjoy !