Exploring SWIFT


Should have posted this a long back, but just got the perfect time to get it done. 

I got a chance to develop an e-Commerce mobile application targeted at iOS8. We decided to develop it using the latest technologies, so we chose to use the SWIFT language released by Apple in Conjunction with iOS8.


SWIFT is a safe, modern and powerful Language, it has a lot of interesting, time saving features, which could allow us(Developers) to focus/work more on the Application’s logic rather than the coding itself.


Swift’s shorthand syntax makes us to write less code when compared to Objective C.
It was a great decision to remove the semicolons(At the end of each statement), Braces (In Control Flows), Subscripts, Enumerations, etc…


Some of the very interesting stuff includes:
  • Optionals
  • Tuples
  • Closures
  • Access Control


Going briefly into those interesting stuff, that mostly adds value to our code/time.


Optionals:
The most interesting and powerful feature that we liked in Swift is “Optionals”. We can’t  imagine, how many times we have checked for nil value in Objective-C as given below.


NSString *string = someFun()
if (string != nil){
//do some stuff with the returned string here
}


SWIFT provides optional variables to solve this issue.


func findNumber (number: String, numbers: [String]) -> String? {
       for tempNumber in numbers {
           if ( tempNumber == number) {
               return number
           }
       }
       return nil
   }


        let foundNumber = findNumber("9890878909", numbers: numbers) //Inferred type String?


So, the “foundNumber” constant is inferred as optional and has a value or nil. To use its value, we need to use “!” operator to unwrap its value like this:
“foundNumber!”
It will return the value, if it has one or else the unwrapping would eventually fail.


Swift also provides Optional Chaining, which allows us to omit the chaining of function calls.
For Example:
           let foundPhoneNumber = findNumber("9890878909", numbers: numbers)?.toInt()



Tuples:
Tuples allows to bind two or more typed values organized into a single entity. We used that way to display appropriate messages for the HTTP Status code.
// tuple
let InvalidPasswordErrorCode = (401, "Invalid Password")
let InvalidEmailErrorCode = (404, "Invalid Email")
// show how to access the contents
//
let namedTuple (param1:Double, param2:String) = (402, “Some string here”)
// show how to acces the contents


Numerous times, we have worried for Methods in Objective-C not having Multiple Return Types. Tuples were introduced to solve such problems.


func MinusAndPlusValues(value:Double) -> (minus:Double, plus:Double) {
 return (value-10, value+10)
}
let minusPlus = MinusAndPlusValues(20.4)



Closures:
Closure is an inline-function or block of functionality that can be passed and used in your code. Closures in Swift are similar to the Blocks in Objective C.Just like blocks, it can capture and store the references of any constants & variables during which they are defined.
We used closures mostly as callback functions, when an API call returns a response.


           manager.registerUser(nameTextField.text, email: emailTextField.text, password: passwordTextField.text, zipcode: zipcodeTextField.text, success: { (responseObject:AnyObject!) in
               }
               }, failure: { (error:AnyObject!) in
          })




Access Modifiers:
This is a great addition to the Swift.
Swift provides 3 levels of access for the entities in the source code.
Public - Provides access to any class within or outside the module or framework.
Internal - Provides access to any class within or inside the module.
Private - Provides access only to the code inside the source file in which it is defined.


Example:
  • public class SomePublicClass {}
  • internal class SomeInternalClass {}
  • private class SomePrivateClass {}


The “SomePublicClass” can be accessed by any class from the project, “SomePrivateClass”, can be accessed only by the code inside the source file where this method is defined, whereas “SomeInternalClass” can be declared with or without the Access Modifier Level included, since “internal” access modifier is the default one.


Some other Interesting stuff Include:


Header Files:
Swift don’t have 2 different files for Header/Implementation, both are merged as one.
Coming from the Objective C background, it was hard to get rid of the Header Files, which was great at separating your declarations with the actual implementation, but overtime it did make sense, since most of the time, you don’t really need that stuff. it did reduce the useless declarations, thus getting rid of the redundant code.
Another really useful feature is that Swift won't ask you to import the header of any class to use the entities of that class. it just auto detects and imports them on its own, whenever you needed it.


Properties:
Another great feature is how Properties are used in Swift.
There are only 2 types: Constants & Variables, which are declared with “let” & “var” keywords.
Example:
Constant: let myConstant: Int = 20// Constant of type Int
Variable: var myVariable: String = “My Variable”// Variable of type String


You don’t have to declare or synthesize the properties, instead you just provide the access levels to access from other classes and use “self.” to access from the closures. That’s it.


Operating between Objective C & Swift:
It was a Wise/Necessary decision to provide interoperability between 2 languages for Apple’s Flagship devices. Meanwhile, it is also so simple to interoperate for the developers.
You just need to create a separate file (Even that is done by Xcode for you) that contains(Imported using the import keyword) the headers/names of the classes that needs to be interoperated that bridges between Swift & Objective C.


Conclusion:
Overall, it was a pleasing experience working with Swift.

Swift is still an evolving language and the changes are been added into it occasionally and hence the language remains incomplete in exploration.

Comments

Popular posts from this blog

Free Hand Drawing on Google's Map View

Android from iOS Guy's Perspective

Free Hand Drawing on Maps with MapBox SDK