Tuesday, December 2, 2014

Swift programming for C# programmer

As soon as I heard about Swift, I immediate let go of Objective C and jumped to it. As a  C# programmer for more than a decade, I immediate fall i love with it.

this post is meant for my own learning note more than anything else. to start I will list down the language elements in Swift and provide correspondent language element in C#.

string interpolation : String.Format 
Delegate ( Protocol ) : Interface
Tuple : Anonymous types, Tuple
optional variables (int? optional int) : nullable  (int? nullable in) 
fforced unwrapping (optionalInt!)  : NummableInt.Value
Closure : Aanonymous delegate 
Property : Automat Property 
object
 default initializer (init): default constructor  (<class name>)
customized initializer : overloaded constructor
forward (self) : this
de initializers (dinit) :  destructor (~<class name>) : same as C#, in most of cases, you do not need to provide de-initializer to your class, as ARC does it job well.
supper class (super) : base class ( base)
initializer delegation : constructor overloading
Designated Initializers and Convenience Initializers : None. limitation : super.init in the sub-class only can call the Designated initializer of the super class. as a .net programmer, you will find it less friendly than that of C#.
Compute Property : normal property / read only property
Type Members : Static Member ( limitation : it must be compute property. it is not supported for stored property)
lazy property : there is no direct language element for it in .Net. however, it can be implemented in the getter of a property
property observers : this language element is absent in C# 4.5. it is very interesting. the following is an simple example:
var lastName : String {
        willSet {
            println("last name is about to be changed to \(newValue)")
        }
        didSet {
            println("last name was changed from  \(oldValue)")
        }

    }

access modifiers (public, internal, private) : in C# there is one more, which is protected. and they can be used in combination. e.g. internal protected. Form this point of view, Swift is lagging behind.