Swift - Rushing to translate ObjectiveC code

Like it or not, swift is swiftly (pun intended) catching up and every 3rd tweet is related to swift. The only problem as I mentioned in the previous article is using swift based on a previous experience with Objective-C and thereby disregarding using the features of Swift.
This is exactly what will happen because of the Gold Rush for everyone to prove their mastery over the language either to get more traffic or to show their mastery over this new found language or finally to promote their training.

So what is this about? Here's the article that led to the validation of this statement.

The first line in the article is creating an imageCache which in the old way of using Objective-C would be to create a dictionary object and to be able to add or remove items from it, it would have to be a mutable object. So one would use an NSMutableDictionary. So this article uses the swift code as
  var imageCache = NSMutableDictionary()

this is the classic mistake that one would make. One of the nice features of Swift is to create Arrays or Dictionary Objects easily. The array or Dictionary objects declared with var are mutable and the ones with let are immutable (there are exceptions and other complex issues, but for simplicity, that’s how it is). So the code
 var imageCache = []

would create a mutable array of items that are of type UIImage. Now adding or removing items is easy and as simple as
 imageCache.setValue(object, forKey: strKey)

This is one of the little ways that Swift will be used. It reminds me of a student that worked on a PHP project that was created like a C++ project, it was rock solid like a tank and equally complex. The whole idea of Scripting languages like Lua, Ruby is to relax and the pre-compiler checks in Swift help to reduce the errors while still offering flexibility in development.

This is the exact thing that many that (non-native english speakers) will instantly realise how sometimes sentences are literal translations of a sentence from the native language to english. This is similar where the code is translated from Objective-C to Swift, it works, but it does not take advantage of the features offered in swift.

Hope that there are many more articles on using swift but it would be nice if the authors would not rush to simply push articles but rather spend time with the language and understand the way of the swift ;)

The same thing when tried in Lua would look something like this

 local imageCache = {}

 local img1 = loadImage("imagename.png")
 imageCache["Test'] = img1

The only thing to note is that loadImage is a function that would change depending on the framework that you would want to use.

Comments

Popular Posts