Swift 3.0 explained for C# Developers

Originally posted on February 02, 2016 | Modified to Swift 3.0 on October 01, 2016

Programming languages provide a way to communicate with a computer through notational instructions.Swift and C# are High-Level Languages commonly categorized under multi-paradigm and Compiled Programming languages. They not only fall into the same category of programming languages but also have many syntactical features in common.Due to this syntactical resemblance, C# developers can easily adapt Swift Programming Language for iOS, macOS, watchOS, tvOS and Linux development.In this post, we will touch upon the key similarities between C# and Swift precisely,

and other key Swift features
You can try the swift code snippets in IBM Swift Sandbox, a tool that allows anyone to write and run Swift code from their browser.

Const is let and var is still var

A Constant is an identifier with a value which cannot be modified during the normal execution of a program.

In C#, Constants are defined using keyword const and the syntax for defining a constant is

In Swift, Constants are defined using let and explicitly defining a type is optional as it picks the datatype based on the “value” which is provided through type inference.

A semicolon (;) at the end of each statement is optional in Swift. However, semicolons are required if you want to write multiple separate statements on a single line.

Note: In C#, When defining a constant symbol, its value must be determinable at compile time. Whereas in Swift, The value of a constant doesn’t need to be known at compile time, but must have a value assigned exactly once with explicit type defined.

Similar to C#, var is the keyword to define a variable in Swift.

Note:As C#, Swift is also type safe.It performs type checks when compiling your code and flags any mismatched types as errors. This enables you to catch and fix errors as early as possible in the development process.

Classes and objects

A class is a blueprint defining the data and behavior of a type. An object is an instance of a class created dynamically with a block of memory allocated. Properties, Methods, Fields are the members of a class.

In C#,

Similarly, In Swift 3.0

Try it on Swift Sandbox

Note: Methods are functions that are associated with a particular type. Also If a method accepts more than one parameter, Named Arguments can be used the same way as in C#. E.g., var employee = Employee(name: “Jones”, Id: 12345).

Class and Interface (Protocol in Swift) Inheritance

Inheritance is one of the primary pillars of object-Oriented Programming. Inheritance is all about reusability of the code.A new class can be created from an existing class.

We can achieve Multiple inheritance through Interfaces in C# and Protocols in Swift. Interfaces and Protocols are just contracts without any implementation. The Syntax is similar to the class declaration.

Note: Prevent override by using  final modifier. Try it on Swift Sandbox

In C#,

In Swift 3.0,

Lambdas are Closures in Swift

Lambda expression introduced in version 3.0 of C# language is an expression which returns a method. The expression Lambdas are expressed in the following basic form in C#,

(input parameters) => expression

In Swift, The Closure Expression takes the following general form,

{ (parameters) -> return type in
statements
}

Sorting a list of names is a herculean task for any developer. So here’s an example showcasing the beauty of Lambdas/Closures.

In C#,

Note: Just for the sake of comparison and understanding, I am using a C# Console application for the code snippets below.

Once you run the code in Visual Studio, You should see an output as shown in the figure below.

C# Console application output.
C# Console application output.

In Swift 3.0,

Try it on Swift Sandbox to understand Swift 3.0 API Design guidelines compared to the previous versions of Swift.

Swift output as seen in IBM Swift Sandbox (in a browser)

IBM Swift Sandbox
IBM Swift Sandbox

Generics are Generics in Swift

C# provides generics to remove the need for casting, improve type safety, reduce the amount of boxing required, and make it easier to create generalized classes and methods.The generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define.

Generics in C#,

Generics in Swift 3.0,

Try it on Swift Sandbox to understand what are the syntactical changes in Swift 3.0 compared to the previous versions of Swift.

Note:

  • If you do not want to use an external name for the second or subsequent parameters of a function, write an underscore (_) instead of an explicit external name for that parameter.
  • Swift uses string interpolation to include the name of a constant or variable as a placeholder in a  longer string and to prompt Swift to replace it with the current value of that constant or variable.

Along with the features mentioned above, Swift provides some power features which makes coding smooth and bug-free.

  • Optionals: Optionals say either “there is a value, and it equals x” or “there isn’t a value at all- nil”. In a way, Similar to Nullable types in C# but Optionals are more expressive and safe. Check unwrapping to understand what I mean.
  • Optional Chaining: Think of a scenario where we are calling a method or talking to a property depending on an Optional which might currently be nil. Swift provides an option to gracefully cut the method call or property talk if the optional is nil. Note: Optional Chaining is an alternative to Forced unwrapping
  • ARC: Object life cycle management is an overhead for a developer as it has a direct impact on memory management which affects the app performance.Here comes Automatic Reference Counting (ARC) to the rescue, When an instance is no longer needed, ARC frees up the memory used by that instance so that the memory can be used for other purposes instead. This ensures that class instances do not take up space in memory when they are no longer needed. It looks like Garbage Collection(GC) in .NET world but the approach is different. Which one is better? The answer is always debatable.
  • Guard: Guard is a conditional statement which helps in an Early Exit if a condition is not met. Unlike an if statement, a guard statement always has an else clause—the code inside the else clause is executed if the condition is not true. Also, any variables or constants that were assigned values using an optional binding as part of the condition are available for the rest of the code block that the guard statement appears in.
  • Property Observers: To observe and respond to changes in a property’s value Property observers are called. Property observers are called every time a property’s value is set, even if the new value is the same as the property’s current value.You have the option to define either or both of these observers on a property:
    • willSet is called just before the value is stored.
    • didSet is called immediately after the new value is stored.
    • willSet and didSet cannot be called when a property is set in an Initializer – init

What we discussed till now is just a drop in the ocean. There are many features which have similar syntax in C# and Swift. Structs, Enums, Loops (Control Flow) are few of them which you can explore and if you are struck anywhere feel free to drop a comment in the comments section below.

What’s next? Check Official Swift Documentation & API Design Guidelines

Also, Build Powerful, fast and Secure Server-Side Swift Apps  on Cloud.

Happy Swifting!!!

(Visited 4 times, 1 visits today)

Vidyasagar Machupalli

Polyglot & Pragmatic Programmer • Developer Advocate, IBM • Microsoft MVP • Intel software Innovator • DZone MVB