Recently, Apple announced and released a beta version of the newSwift programming LanguageFor building IOS and OSX applications. Swift is a modern language with the power of objective-c without the "baggage of C." While we can ' t argue that objective-c have it ' s difficulties being tied closely to C, but the real question is ... How does Swift compare to a modern language like C #?
Please, keep-in-mind-this-post is not supposed-to-be-an Apple vs Microsoft post. There is a lot of developers so use C # every day and the purpose of this post was to help them understand what Swift off ERs at a language level compared to C #. And, before you start the "apples and oranges" arguments, it's worth pointing out of that usingXamarinYou can develop IOS and OSX apps using C #.
Now let the code mostly speak for itself ...
Code Comments
Both languages support the same syntax for code comments; The familiar C-style comments.
- Code Comment
- /* Multi Line
- Code Comment */
Copy Code
Declaring Constants and Variables
Swift, like C #, is a type safe language. It also supports type inference so you don't have to specify the type when declaring the variables as the compiler can INF ER (or detect) the type by evaluating the assignment of the variable. While C # is slightly more verbose when declaring constants; Both languages is just as elegant at declaring variables using type inference.
- Declare Constant
- C#
- const int legalage = 18;
- Swift
- Let Legalage = 18
- Declare Variable
- C#
- var legalage = 18;
- Swift
- var legalage = 18
Copy Code
While type inference are nice, if you don't immediately assign a value to the variable your need to explicitly spe Cify the type of the variable.
- Type Annotation
- C#
- String FirstName;
- Swift
- var firstname:string
Copy Code
Notice the lack of the semi-colon in Swift. Yes, Swift is a mostly c-style syntax without requiring semi-colons. Swift does support and require the use of semi-colons if you want to has multiple code statements on the same line.
Variable Names and Unicode
Both languages support the use of the Unicode characters as variable names. Basically, you could use emoticons or other NON-ASCII characters as variable names if you want and who does that anyway?
Integer Bounds
Both languages has static constants for accessing, the minimum and maximum bounds for the different Integer types.
- Integer Bounds
- C#
- var a = Int32.minvalue;
- var B = Int32.MaxValue;
- Swift
- var a = Int32.min
- var B = Int32.max
Copy Code
Type Inference
Both languages, as mentioned above, support type inference where the compiler are able to detect what type the declared Var Iable is from it ' s immediate assignment.
- Type Inference
- C#
- var a = 3; Integer
- var B = 0.14//double
- var C = a + B; Double
- Swift
- var a = 3//integer
- var B = 0.14//double
- var C = a + b//double
Copy Code
Also in the above type inference example you ' ll notice so when you declare a variable and immediately assign a value tha T is the result of 2 other variables it would still infer the type.
String Comparison
Both has similar methods of comparing strings.
- String Comparison
- C#
- var a = "one";
- var B = "one";
- if (a = = b) {
- Both variables is considered equal
- }
- Swift
- var a = "one"
- var B = "One"
- If a = = b {
- Both variables is considered equal
- }
Copy Code
The both also has similar methods of detecting if the beginning or ending of the string match ' s a specified string.
- C#
- var s = "Some Value";
- if (S.startswith ("Some")) {
- The string starts with the value
- }
- if (S.endswith ("Value")) {
- The string ends with the value
- }
- Swift
- var s = "Some Value"
- If S.hasprefix ("Some") {
- The string starts with the value
- }
- If S.hassuffix ("Value") {
- The string ends with the value
- }
Copy Code
Notice from the above example that parenthesis is not required with IF statements in Swift.
String Upper or Lower case
Both languages support similar methods of converting strings to Upper or Lower case.
- String Upper and Lower case
- C#
- var s = "some Value";
- var uppers = S.toupper ();
- var lowers = S.tolower ();
- Swift
- var s = "Some Value"
- var uppers = s.uppercasestring
- var lowers = s.lowercasestring
Copy Code
Declaring Arrays
Both languages support declaring and assigning Arrays using a single line of code.
- Declare Arrays on single line
- String Array
- C#
- var arr = new string[] {"One", "one"};
- Swift
- var arr = ["One", "both"]
- Integer Array
- C#
- var arr = new int[] {1, 2};
- Swift
- var arr = [1, 2];
Copy Code
Working with Arrays
Working with Arrays has slight differences between the languages.
- Iterating over Array
- C#
- foreach (var item in arr) {
- Do something
- }
- Swift
- For item in arr {
- Do something
- }
- Get Item at Index
- C#
- var item = arr[0];
- Swift
- var item = arr[0]
- Set Item at Index
- C#
- Arr[0] = "Value";
- Swift
- Arr[0] = "Value"
- Is Array Empty?
- C#
- if (arr. Length = = 0) {
- Array is empty
- }
- Swift
- If Arr.isempty {
- Array is empty
- }
- Add Item to Array
- C#
- Array.resize (ref arr, arr.) Length + 1);
- Arr[arr. LENGTH-1] = "three";
- Swift
- Arr.append ("three")
- Or
- Arr + = "three"
- Remove Item at Index
- C#
- var list = arr. ToList ();
- List. RemoveAt (0);
- var newArr = list. ToArray ();
- Swift
- var newArr = arr.removeatindex (0)
Copy Code
Declaring dictionaries
Both languages support similar methods of declaring dictionaries.
- Declaring dictionaries
- C#
- var dict = new dictionary<string, string> ();
- var dict2 = new dictionary<string, string>
- {
- {"Tyo", "Tokyo"},
- {"DUB", "Dublin"}
- };
- Swift
- var dict = dictionary<string, string> ()
- var dict2 = ["Tyo": "Tokyo", "DUB": "Dublin"]
Copy Code
Working with Dictionaries
Working with dictionaries has slight differences between the languages.
- Iterate over Dictionary
- C#
- foreach (var item in dict) {
- var key = Item. Key;
- var value = Item. Value;
- }
- Swift
- For (key, value) in Dict {
- Key variable contains key of item
- Value variable contains value of item
- }
- Get Item in Dictionary by Key
- C#
- var item = dict["Tyo"];
- Swift
- var item = dict["Tyo"]
- Set Item in Dictionary by key
- Or add if key doesn ' t exist
- C#
- dict["LHR"] = "London";
- Swift
- dict["LHR"] = "London"
- Remove Item in Dictionary by key
- C#
- Dict. Remove ("LHR");
- Swift
- Dict.removevalueforkey ("DUB")
Copy Code
For Loops
The above examples for Arrays and dictionaries already showed examples of using a for-in loops to iterate through the items In those collections. Here is some additional methods of iterating using a for loop.
- Iterate from 1 through 5
- C#
- Using increment
- for (var i = 1; I <= 5; i++) {
- Do something with I
- }
- Swift
- Using range
- For I in 1...5 {
- Do something with I
- }
- Using increment
- for var i = 0; I <= 5; ++i {
- Do something with I
- }
Copy Code
The range example of rather interesting in the method of shorthand it uses for it ' s definition.
Conditional statements
Both languages Support If ... Then conditional statements. Swift is a little different that it doesn ' t require parenthesis around the match conditions.
- If then Else Conditional Statement
- C#
- if (i > 6) {
- Do something
- } else if (i > 3 && I <= 6) {
- Do something
- } else {
- Do something
- }
- Swift
- If I > 6 {
- Do something
- } else if i > 3 && i <= 6 {
- Do something
- } else {
- Do something
- }
Copy Code
Switch Statement
Both languages Support Switch statements.
- Switch statement
- C#
- var word = "A";
- Switch (word) {
- Case "A":
- Do something
- Break
- Case "B":
- Do something
- Break
- Default
- Do something
- Break
- }
- Swift
- var word = "A"
- Switch Word {
- Case "A":
- Do something
- Case "B":
- Do something
- Default
- Do something
- }
Copy Code
Switch statements is rather similar in both languages except so in Swift case statements don ' t automatically pass over to The next like in C #. As a result C # requires the use of the keywords to exit the Switch statement, unless you want to fall through to the Next case. While in Swift must use the "fallthrough" keyword-to-tell it-pass on through to the next case statement. More information on this can is found in the Swift documentation.
An additional feature, Swift supports with Switch statements are ranges within the case statements. This was something that C # does not support.
- Switch Case Ranges
- C#
- switch (i) {
- Case 1:
- Case 2:
- Case 3:
- Do something
- Break
- Case 4:
- Do something
- Break
- Default
- Do something
- Break
- }
- Swift
- Switch I {
- Case 1...3:
- Do something
- Case 4:
- Do something
- Default
- Do something
- }
Copy Code
Functions
WhileFunctions is a much bigger comparisonTo is made, here's a basic example:
- Function with Parameter and Return Value
- C#
- String SayHello (string name) {
- Do something
- }
- Swift
- Func SayHello (name:string), String {
- Do something
- }
Copy Code
The PostBasic Comparison of Functions in C # and SwiftGoes to much more depth on Functions; As that was a much bigger comparison that could fit to this post.
Conclusion
This concludes my basic comparison of C # and Apple Swift programming languages. The languages is rather similar in many respects; At least in what I ' ve compared thus far. More language feature comparisons would have the to-wait for the future posts.
One of the bigger differences that's worth pointing out explicitly are the difference in what each language handles Array ' s. Arrays in Swift is extremely similar to the List<> class in C #; Which is what the most developers use today in C # instead of arrays anyway (unless performance requires it.)
You can find more information about the Swift programming language on Apple's site at the following links:https://developer.apple.com/swift/https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/
Basic syntax comparison of Swift and C #