Interesting Swift: overview of some interesting things in swift

So I am playing with swift a little bit for this holiday, and found out it to be very interesting language to play with, they actually designed many things that is actually more interesting than the languages I am very used to with. This blog is possibly not going to be a blog that I would refer people to read for learning as I am mentioning java, python or ruby all the way I am going with this blog and not everyone is supposed to be aquatinted with these language, but I am doing it get away with the feeling that I had while playing around.

So far I could find two ways in swift to initialize variables either var or let. var is for variables that actually varies and let is something that remains the same forever. Java has its constant using final that prevented us from changing the variable values once it got initialised. Ruby ensures it by putting its variable name all capital, which I am not a great fan of. Python does not provide much straight forward support for constants. I personally like constants because I believe internally at programming language implementation level it should give compliers and interpreters enough power to optimize and it helps me to reduce bugs in my code as I would have full control over the code on what I am doing and what the variable is intented to be doing even after passing my code to some one else to modify or add more features. Not to mention I have every freedom whether to define a variable with an associated type or let the initialized value to infer its type, which was also great. Although it is considered as a bad coding style to let swift not to infer the type.

var text: string = "hello world"
var text = "hi world"

lazy vars are also interesting, I actually never thought of something like that as I thought compilers or other optimizations tool we are using would take care of that. When we declare a variable as lazy variable, swift initialize that variable when it is absolutely required.

It is also interesting and very useful I believe the way swift syntax is taking care of if variable is initializaable or not.

if (let text = button.currentTitle){
 //display.text = display.text + text  
}

Python has a different syntax idea about ternary operations where java, ruby has almost the same syntax as swift.

output = a != nil ? a! : b

Some short hands on ternary operations comes handy like ruby:

output = a ?? " "

This is interesting that swift won’t allow me to put a variable without we initializing it. Or we have options for definiting a variable as optional when we are not intending to initialize it, now what are optionals? Glad that you asked.

Optionals are actually very interesting concept to me, In ruby code, while using other peoples API send? and send! with a bang, these variations of name actually told me a lot of details and safetly measure required or not on that methods by convention. It felt like swift took it to the next level, so far as my introductory tutorial states some of the properties of an instance can be optional type as well, that is being represented with a question mark in the end, like String?, that is just a special string. Optional actually can be used for chained calls and if it fails to reach to the end of the expression it returns nil. So it saves us from writing a lot of lets and if clauses.

let x = display?.text.hasValues{}

point to note that, x will be an optional in that case because we can never get a value return from this kind of chained methods.

We even can define this optional strings in our code.

var label: String?;

Its interesting and completely make sense that for getting back data from dictionaries we get an optional type in return. Also AnyObject is a type that takes anything and everything through a parameter or pretty much anywhere as a type but we might want to use as to treat that anyobject to something else let foo=ao as? String{}. as is just casting it to another class.

These special we actually need to take special care when handling with these optional properties. We need to unwrap that variable with a bang(!).

func touchButton(button: UIButton){
 let text = button.currentTitle!
 print("pressed \(text) button")
}

I have mentioned earlier that you can’t define a variable when you do not initialize it. Let me add more information to that statement, we actually can implicitly unwrap a variable while defining it as well, that will reduce our burden of unwrapping it every time we intended to use it.

var display: UILabel!
print("\(display.text)")

var cash: Double {
set: {
  return Double(label.text!)
}
get:{
  label.text = cash
}
}

Apart from computed properties, there are actually few other interestng properties too, like observer properties. willset and didset could be one of them.

Swift function declaration could be very interesting as well, we can define internal and external parameters in swift functions, internal parameter has scope locally when external parameters are the parameter the callee of the method has to fullfil.

Like python it provides options for positioned parameter, in swift it can be done using an underscore before the parameter name, which I did not like most, but it is how they speak swift.

Java has some support for lambda expressions, python and ruby has way better support for it though. My first impression on swift anonymous methods was pretty interesting, I would say, it is even easier.

{str1 :String, stt2:String} ~> String in
return str1 + str2

Swift has options for anonymous abstract methods as well, which can be written as following:

(Double, Double)~> Double

Need to mention that in like python or ruby functions are also considers as object in swift. So does this previous implementation of abstract class. I will be talking about its use cases in a while.

Speaking of enums I am not a great fan of python or ruby enums so I would deliberately avoid talking about them, Java has great support for enums, it supports internal methods in enum which is great, I am glad that swift also supports internal methods like java even more interesting way actually. I guess in java I did not have the credibility to use separate initializer for separate cases, what swif offers,

enum MathOperator{
 case None
 case Constant(Double)
 case Unary((Double)~> Double)
 case Binary((Double, Double)~> Double)
}

As you can see, now we have options to define our enums with so many informations, even with functions.

We can have a dictionary of our operatons like following in swift:

let operations: Dictionary<String, MathOperator> ={
 "e": MathOperator.Constant(M_E),
 "±": MathOperator.Unary(sign_change),
 "+": MathOperator.Binary({op1 :Double, op2:Double} ~> String in
  return str1 + str2
 )
}
func sign_change(number: Double) ~> Double{
 return -1* number
}

Now when we need to use this we can use swift switch statements, point to note on swift switches are they are not fall through like typical switches, if we want it then we would need fallthrough to make it fall to next case:

func sign_change(number: Double) ~> Double{

 if let op = operations["+"]{
   switch op:
    case .Constant (let value):
      return value
    case .Unary (let function):
      return function(input1)
    case .Binary(let function):
      return function(input1,input2)
 }
}

Java does not support struct, but as far as I know there are ways to implement struct like objects in java, I have heard people saying that. I have read, and seen people bundling properties in struct in ruby and python, I have used struct for classes for temporary uses and data bundling in ruby. In swift I think it has huge scope for using it for temporary classes, I have been warned that every time I am creating a class it is possibly taking a whole new space in the memory unlike a class reference. So I need to be a little bit warned when using structs, but swift has its own beautiful way to manage it, like every time only when the data changes in swift struct it consumes the memory and it has intelligence to figure out which part of data it need to reallocate, not all of them always. Enums or structs stores its properties as a constant so we can’t change it without recreating the struct in the heap and there are special ways to do that using function like putting mutating func while declaring a function.

I really liked the way I can ensure type order in swift touples, I missed this sort of declaration while working in python as I wanted to have somewhat a gurantee that a function return type will be somewhat fixed.

let x: (String, Int, Double) = {"hello world", -1, 0.2}

Recently i had a great fight with python ands its unicode to make a work done perfectly. We need to add special comments at the header of script. Swift was a lot programmer friendly in that regard, Swift unicodes are full unicodes.

I guess sometime I will have to use objective C codes, as the tutor mentioned about NSObject class. To use some of the objective c apis I would need to inherit NSObject class. It has many other NS objects, I don’t think it would be very interesting thing to talk about. So deliberately ignoring them.