Apple Swift

Many developers always dream of creating iOS application but getting started with objective-C language isn’t easy. But now, thanks to Swift, this problem may be resolved. Many concepts on Swift come from modern language that we have already worked on before.

Swift is Very Similar to C#

Variables and Constants

The first huge thing that Swift provides is type inference so type declaration is not mandatory. The compiler can detect the type by evaluating the assignment of the variable. Microsoft added this feature to .NET 3.0 and it’s practically mainstream.

Swift C#, F#
var quantity = 10
var price : Double = 1500.99
let tax = 2.99 // constant
var quantity = 10;
double price = 1500.99;
const double tax = 2.99
let tax = 2.99 // F# language 

The first thing we can see in Swift is the disappearance of the semicolon at the end of each statement. Swift language constants are declared by using the let keyword, variables are declared by using the var keyword. In the C# language, variables are also declared by using the var keyword and in F#, the let keyword is used to declare a value too. When variable isn’t immediately assigned a value, it needs to explicitly specify the type of the variable.

Swift C#
errCode: String
string errCode;

Swift introduces the new optional types. Optionals allow us to indicate a variable that can either have a value, or nullable. Swift’s optionals provide compile-time check that would prevent some common programming errors that happen at run-time. Once we know the optional contains a value, we unwrap optionals by placing an exclamation mark (!) to the end of the optional’s name. This is known as forced unwrapping. It is similar to declare nullable variable in C#.

Swift C#
var findNumber: Int? // Null value
if (findNumber != nil )
    { var searchValue = findNumber! }
int? findNumber;
if (findNumber.HasValue)
    { var searchValue = findNumber.Value; }

String methods such as converting strings to upper or lower Case, determining whether the beginning/end of this string instance matches the specified string are very alike.

Swift C#
var strName = "iPhone 6"
if strName.uppercaseString.hasPrefix("IP")
    {    // to do     }
if strName.lowercaseString.hasSuffix("6")
    {   // to do      }
var strName = "iPhone 6";
if (strName.ToUpper().StartsWith("IP"))
    {     //to do    }
if (strName.ToLower().EndsWith("6"))
    {     //to do     }

Another favorite feature of Swift is string template that can be used to build a string using variables constants as well as the results of expressions by putting them on the “()”. C# can do the same thing by using string format.

Swift C#
var total = "Total: (price * Double(quantity))"
var total = String.Format
("Total {0}", price * quantity);

Array

The syntax of declaring an array in Swift is slightly different to that in C# but has very similar ability. Some functions are the same implementation. We can map line by line the sample below:

Swift C#
var arrayItem: [String] =  ["iPhone","iPad"]
// for-in loop
for item in arrayItem {   // to do     }
// check  empty
if arrayItem.isEmpty {    // to do   }
// Get item by index
var first = arrayItem[0]
// Set item by index
arrayItem[0] = "Macbook"
// remove item
arrayItem.removeAtIndex(0)
var arrayItem = new string[] { "iPhone", "iPad" };
// for-each loop
foreach (var item in arrayItem)    { // to do }
// check  empty
if (arrayItem.Length == 0)   { // to do   }
// Get item at index
var first = arrayItem[0]
// Set item by index
arrayItem[0] = " Macbook "
// remove item
var list = arr.ToList();
list.RemoveAt(0);

Just like variables, Arrays are strongly typed by default and by this way, Swift is pretty much the same as JavaScript.

Swift C#
var arrayItem  =  ["iPhone","iPad"]
var arrayItem  =  ["iPhone","iPad"];

In my opinion, Arrays in Swift are extremely similar to the List in C#.

Dictionary

Both C# and Swift have a very similar approach but declaring and iterating are slight differences but it looks like a small thing.The table below depicts dictionary functionality on both Swift and C#.

Swift C#
var listItem: Dictionary<int, string=""> =
     [1: "iPhone", 2: "iPad"]
// Iterate dictionary
for (key, value) in listItem
    {   // todo key and value   }
// set item to dictionary
listItem[3] = "Macbook"
// Remove item out dictionary by key
listItem.removeValueForKey(2)
// Get item from dictionary by key
var first = listItem[1]
var listItem = new Dictionary<int, string>()
    {{1, "iPhone"}, {2, "iPad"}};
// Iterate dictionary
foreach (var item in listItem)
   { // todo item.key and item.value     }
// set item to dictionary
listItem[3]="Macbook";
// Remove item out dictionary by key
listItem.Remove(2);
// Get item from dictionary by key
var first = listItem[1];

We can remove an item in Swift by assigning to nullable (Listitem[2]= nil), it looks like JavaScript coding.

If Condition

Swift doesn’t require parenthesis “()”around the match conditions. Parentheses are optional but it is important that if statement must be opened and closed with brace brackets “{}” even if the code resolves only one line. In C# in case if statement is resolved in one line, it is not necessary to put in brace brackets. The reason is Apple wants to make swift as the safe language, prevents some unexpected bugs such as the Apple’s SSL “goto fail” issue Apple faced before:

if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
        goto fail;
        goto fail;  /* MISTAKE! THIS LINE SHOULD NOT BE HERE */

“ goto fail” was called two times. It seems that this bug was likely caused by developer when copying and pasting but a small code issue can be catastrophic. The sample below compares if condition between Swift and C#:

Swift C#
if searchItem  == "iPhone" // don't need ()
    {   vat = 1.99   } // must have  {}
else if searchItem  == "iPad"
    {    //todo   }
else
    {   //todo    }
if (searchItem  == "iPhone")
   vat = 1.99 ; // Don’t need  {}
else if (searchItem  == "iPad")
   {  //todo    }
else
   {   //todo     }

Switch statement

Switch statement in Swift is also a strong resemblance to the C# syntax. But in Swift, “break” statement is not necessary and default clause is mandatory.

Swift C#
switch index {
    case 0: // to do
    case 1: // to do
    default: // it is mandatory.
}
switch (index) {
    case 0: break ;// to do
    case 1: break ;// to do
    default: break;
}

One feature Swift supports with Switch statements is ranges within the Case statements, this case seems Swift is more simple than C#.

Swift C#
switch index {
    case 0, 1: //  multiple value
    case 2...10: // multiple value
    default: // todo }
switch (index) {
    case 0:
    case 1:
    break;  // todo
    default: break; }

for – while – do … while

Swift provide the basic for, while and dowhile loops very C#-like syntax. It is lucky that there are no significant syntax changes. The only difference is that there are no parentheses in Swift around the conditions.

Swift C#
// For loop
for var i = 0 ; i < 100 ; ++i  {  // to do  }
 // while
while !done  {  // to do  }
// do .. while
do  {   // to do  } while !done
// for in range
for index in 1...5  {  // to do   }
// For loop
for(var i = 0; i < 100; i++) {  // to do  }
// while
while !done  {  // todo  }
// do .. while
do  {  // todo } while !done
// for in range
foreach (var i in Enumerable.Range(1, 5)) 
    {  // to do   }

Functions

Like C#, functions are first class citizens in Apple Swift. It means that it allows us to do a lot of useful stuff such as it can be stored in a variable or constant, passed as a parameter, assigned to a value or returned as the result of another function. Basically, there really aren’t many differences between C# and Swift.

Swift C#
func Total(quantity: Int, price: Double) -> Double {
    return Double(quantity) * price     }
// Multiple return values
func getDetail() -> 
    (name:String,quantity: Int, price :Double)
    {  return ("iPhone6",2, 1500.99)   }
// in Out parameter
func swapNumbers(inout a: Int, inout b: Int)
    { var  c = a;  a = b;   b = c; }
// Function Type
var result : (Int, Double) -> Double = Total
//or
var result -> Double = Total
double Total(int quantity, double price)
        {     return quantity * price;   }
// Multiple return values
Tuple<string, int, double> getDetail()
  {  return new Tuple<string,int ,
  double>("iPhone6", 2, 1500.99);   }
// in Out parameter
void swapNumbers (ref int a, ref int b)
   { var c = a; a = b; b = c; }
// Function Type
Func<int, double, double> result = Total;

As both Swift and C# support passing a function as a parameter, function As Return Type, etc., we can see that the basic syntax of them is really similar. There aren’t many differences between the 2 languages as you can see the comparison above.

Protocol

In C#, we have already worked with interfaces and Protocols Swift look like interfaces. The protocol is a set of methods and properties that don’t actually implement any things; it merely defines the required properties, methods. Any class that uses this protocol must implement the methods and properties dictated in the protocol. The important role of protocol may be low coupling between classes.

Swift C#
protocol Purchase
{
    var name : String { get  set};
    var quantity : Int { get  set};
    var price : Double { get  set};
    func Total() -> Double;
}
interface Purchase
{
    string name { get;  set;}
    int quantity  { get;  set;}
    double price { get;  set;}
    double total();
}

Class

The table below depicts how to create class in C# and Swift:

Swift C#
class ItemDetail {
    var itemName : String
    var itemQuantity : Int
    var itemPrice : Double
    init(name: String, quantity: Int, price:Double)
     {
        self.itemName = name;
        self.itemQuantity = quantity;
        self.itemPrice = price;
    }
    func Total () -> Double {
        return itemPrice * Double(itemQuantity)
      }
}
// Access class
var itemDetail =
      ItemDetail (name:"iPhone", 
      quantity: 2, price: 100.99)
public  class ItemDetail {
    private string itemName;
    private int itemQuantity;
    private double itemPrice;
    public ItemDetail  
        (string name, int  quantity,
        double price)    {
        itemName = name;
        itemQuantity = quantity;
        itemPrice = price;
        }
    public double Total ()   {
       return itemPrice * itemQuantity;
          }
}
//  Access class
ItemDetail iTemDetail =
    new ItemDetail ("phone", 1, 1.2);

The way Swift and C# define properties, functions and Constructor class do not look different. It is just a small change about syntax, no big differences. C# developers can learn quickly. Both of them have supported subclass but I like to show how Swift class can conform to a protocol and implement properties, functions of the protocol.

class iPhone : Purchase {
    var name = "iPhone"
    var quantity =  1
    var price = 1500.99
    func Total () -> Double {
        return price * Double(quantity)
    }
}

This is the same way we implement class inheriting from interface in C#.

Extensions

One of the powerful features in Swift is extensions that allow adding new functionality to existing structures such as classes, structs, or enumerations. The way to implement extensions is also very similar to C#. The demo below depicts how to extend array of Swift and C# by adding some functions such as Max, Min and Average:

Swift C#
extension Array {
    var Min: T { // to do }
    var Max: T { // to do }
    var Average: T { // to do }
    }
// call extension
var max = arrayNumber.Max
public static  class ArrayExtension
    public static T Max<T>(T[] arr)    { // to do }
    public static T Min<T>(T[] arr)   { // to do }
    public static T Average<T>(T[] arr)  { // to do }
}
// call extension
var max = ArrayExtension.Max(arr);

Closure

Closures are used to package a function and its context together into an object. This makes code easier to both debug and read. The code below shows how to sort data by closure.

Swift C#
var arrayNumber = [4,5,3]
var list = sorted(arrayNumber, { s1, s2 in
    return s1 < s2 })
List<int> list = new List<int> { 4, 5, 3, };
list.Sort((x, y) => Convert.ToInt32((x < y)));

In general, if we used to work with C#, Swift code isn’t difficult to write.

The closure can effectively express developer’s intent with less code and more expressive implementation. As we used the closure in C#, understanding and using closure is an important factor to being productive in the iOS development.

Generic

Generics are a powerful way to write code that is strongly typed and flexible. Swift built the concept of generics the same C# languages. Using generics, developer can implement a single function that works for all of the types. The search item in array/list function below shows the simple generic implementation:

Swift C#
func indexArray<T :Equatable>
(item :T, array :[T]) -> T?
    {
        for value in array
        {
            if(value == item)
            {
                return value
            }
        }
         return nil
    }
public static Nullable<T>
IndexList<T>(T item, T[] arr) where T : struct
    {
        foreach (var i in arr)
        if (i.Equals(item))
            {
               return i;
            }
           return null;
       }

Actually, the code shows that we can develop Swift application like we work with C#. It is just some small syntax changed.

Points of Interest

There are a lot of similarities between Swift and C#. We can use our existing skills and knowledge when developing iOS applications in Swift. The important thing is now Swift new syntax is a lot more easy to work with, specially to those developers who have .NET background.

Swift isn’t the finished product, Apple is still building Swift. It looks like new features will be added over the coming months. It is worth familiarizing with Swift language.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.