Introduction
This year at World Wide Developer Conference, Apple announced the new language as the future language for iOS and Mac OSX called Swift. It was really the biggest surprise for anyone following Apple. After four years in development, Apple has created and now revealed what will become the foundation of a new generation of applications for both OS X and iOS. Three design principles of Swift are Safety, modern syntax, and powerful features. Going over the new language, it makes me surprised that Swift can be written in a way we implement C#. I would like to show an overview of the new Swift features against C# so that developers who use C# can quickly understand what Swift language offers.
Background
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
|
var quantity = 10;
double price = 1500.99;
const double tax = 2.99
let tax = 2.99
|
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?
if (findNumber != nil )
{ var searchValue = findNumber! }
|
int? findNumber;
if (findNumber.HasValue)
{ var searchValue = findNumber.Value; }
|
String
methods such as converting string
s 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")
{
if strName.lowercaseString.hasSuffix("6")
{
|
var strName = "iPhone 6";
if (strName.ToUpper().StartsWith("IP"))
{
if (strName.ToLower().EndsWith("6"))
{
|
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 item in arrayItem {
if arrayItem.isEmpty {
var first = arrayItem[0]
arrayItem[0] = "Macbook"
arrayItem.removeAtIndex(0)
|
var arrayItem = new string[] { "iPhone", "iPad" };
foreach (var item in arrayItem) {
if (arrayItem.Length == 0) {
var first = arrayItem[0]
arrayItem[0] = " Macbook "
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"]
for (key, value) in listItem
{
listItem[3] = "Macbook"
listItem.removeValueForKey(2)
var first = listItem[1]
|
var listItem = new Dictionary<int, string>()
{{1, "iPhone"}, {2, "iPad"}};
foreach (var item in listItem)
{
listItem[3]="Macbook";
listItem.Remove(2);
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;
“ 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"
{ vat = 1.99 }
else if searchItem == "iPad"
{
else
{
|
if (searchItem == "iPhone")
vat = 1.99 ;
else if (searchItem == "iPad")
{
else
{
|
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:
case 1:
default:
}
|
switch (index) {
case 0: break ;
case 1: break ;
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:
case 2...10:
default:
|
switch (index) {
case 0:
case 1:
break;
default: break; }
|
for – while – do … while
Swift provide the basic for
, while
and do
-while
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 var i = 0 ; i < 100 ; ++i {
while !done {
do {
for index in 1...5 {
|
for(var i = 0; i < 100; i++) {
while !done {
do {
foreach (var i in Enumerable.Range(1, 5))
{
|
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 }
func getDetail() ->
(name:String,quantity: Int, price :Double)
{ return ("iPhone6",2, 1500.99) }
func swapNumbers(inout a: Int, inout b: Int)
{ var c = a; a = b; b = c; }
var result : (Int, Double) -> Double = Total
var result -> Double = Total
|
double Total(int quantity, double price)
{ return quantity * price; }
Tuple<string, int, double> getDetail()
{ return new Tuple<string,int ,
double>("iPhone6", 2, 1500.99); }
void swapNumbers (ref int a, ref int b)
{ var c = a; a = b; b = c; }
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)
}
}
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;
}
}
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 {
var Max: T {
var Average: T {
}
var max = arrayNumber.Max
|
public static class ArrayExtension
public static T Max<T>(T[] arr) {
public static T Min<T>(T[] arr) {
public static T Average<T>(T[] arr) {
}
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.
History
- 5th December, 2014: Initial version