Basic syntax comparison of Swift and C #

Source: Internet
Author: User
Tags case statement ranges switch case

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.
    1. Code Comment

    2. /* Multi Line
    3. 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.

    1. Declare Constant
    2. C#
    3. const int legalage = 18;

    4. Swift
    5. Let Legalage = 18

    6. Declare Variable
    7. C#
    8. var legalage = 18;

    9. Swift
    10. 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.

    1. Type Annotation
    2. C#
    3. String FirstName;

    4. Swift
    5. 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.

    1. Integer Bounds
    2. C#
    3. var a = Int32.minvalue;
    4. var B = Int32.MaxValue;

    5. Swift
    6. var a = Int32.min
    7. 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.

    1. Type Inference
    2. C#
    3. var a = 3; Integer
    4. var B = 0.14//double
    5. var C = a + B; Double

    6. Swift
    7. var a = 3//integer
    8. var B = 0.14//double
    9. 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.

    1. String Comparison
    2. C#
    3. var a = "one";
    4. var B = "one";
    5. if (a = = b) {
    6. Both variables is considered equal
    7. }

    8. Swift
    9. var a = "one"
    10. var B = "One"
    11. If a = = b {
    12. Both variables is considered equal
    13. }
Copy Code

The both also has similar methods of detecting if the beginning or ending of the string match ' s a specified string.

    1. C#
    2. var s = "Some Value";
    3. if (S.startswith ("Some")) {
    4. The string starts with the value
    5. }
    6. if (S.endswith ("Value")) {
    7. The string ends with the value
    8. }

    9. Swift
    10. var s = "Some Value"
    11. If S.hasprefix ("Some") {
    12. The string starts with the value
    13. }
    14. If S.hassuffix ("Value") {
    15. The string ends with the value
    16. }
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.

    1. String Upper and Lower case
    2. C#
    3. var s = "some Value";
    4. var uppers = S.toupper ();
    5. var lowers = S.tolower ();

    6. Swift
    7. var s = "Some Value"
    8. var uppers = s.uppercasestring
    9. var lowers = s.lowercasestring
Copy Code



Declaring Arrays

Both languages support declaring and assigning Arrays using a single line of code.

    1. Declare Arrays on single line

    2. String Array
    3. C#
    4. var arr = new string[] {"One", "one"};

    5. Swift
    6. var arr = ["One", "both"]

    7. Integer Array
    8. C#
    9. var arr = new int[] {1, 2};

    10. Swift
    11. var arr = [1, 2];
Copy Code


Working with Arrays

Working with Arrays has slight differences between the languages.



  1. Iterating over Array
  2. C#
  3. foreach (var item in arr) {
  4. Do something
  5. }

  6. Swift
  7. For item in arr {
  8. Do something
  9. }


  10. Get Item at Index
  11. C#
  12. var item = arr[0];
  13. Swift
  14. var item = arr[0]


  15. Set Item at Index
  16. C#
  17. Arr[0] = "Value";

  18. Swift
  19. Arr[0] = "Value"


  20. Is Array Empty?
  21. C#
  22. if (arr. Length = = 0) {
  23. Array is empty
  24. }

  25. Swift
  26. If Arr.isempty {
  27. Array is empty
  28. }


  29. Add Item to Array
  30. C#
  31. Array.resize (ref arr, arr.) Length + 1);
  32. Arr[arr. LENGTH-1] = "three";

  33. Swift
  34. Arr.append ("three")
  35. Or
  36. Arr + = "three"


  37. Remove Item at Index
  38. C#
  39. var list = arr. ToList ();
  40. List. RemoveAt (0);
  41. var newArr = list. ToArray ();

  42. Swift
  43. var newArr = arr.removeatindex (0)
Copy Code





Declaring dictionaries

Both languages support similar methods of declaring dictionaries.

    1. Declaring dictionaries
    2. C#
    3. var dict = new dictionary<string, string> ();
    4. var dict2 = new dictionary<string, string>
    5. {
    6. {"Tyo", "Tokyo"},
    7. {"DUB", "Dublin"}
    8. };

    9. Swift
    10. var dict = dictionary<string, string> ()
    11. var dict2 = ["Tyo": "Tokyo", "DUB": "Dublin"]
Copy Code





Working with Dictionaries

Working with dictionaries has slight differences between the languages.

  1. Iterate over Dictionary
  2. C#
  3. foreach (var item in dict) {
  4. var key = Item. Key;
  5. var value = Item. Value;
  6. }

  7. Swift
  8. For (key, value) in Dict {
  9. Key variable contains key of item
  10. Value variable contains value of item
  11. }

  12. Get Item in Dictionary by Key
  13. C#
  14. var item = dict["Tyo"];

  15. Swift
  16. var item = dict["Tyo"]


  17. Set Item in Dictionary by key
  18. Or add if key doesn ' t exist
  19. C#
  20. dict["LHR"] = "London";

  21. Swift
  22. dict["LHR"] = "London"


  23. Remove Item in Dictionary by key
  24. C#
  25. Dict. Remove ("LHR");

  26. Swift
  27. 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.

    1. Iterate from 1 through 5
    2. C#
    3. Using increment
    4. for (var i = 1; I <= 5; i++) {
    5. Do something with I
    6. }

    7. Swift
    8. Using range
    9. For I in 1...5 {
    10. Do something with I
    11. }
    12. Using increment
    13. for var i = 0; I <= 5; ++i {
    14. Do something with I
    15. }
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.

    1. If then Else Conditional Statement
    2. C#
    3. if (i > 6) {
    4. Do something
    5. } else if (i > 3 && I <= 6) {
    6. Do something
    7. } else {
    8. Do something
    9. }

    10. Swift
    11. If I > 6 {
    12. Do something
    13. } else if i > 3 && i <= 6 {
    14. Do something
    15. } else {
    16. Do something
    17. }
Copy Code


Switch Statement

Both languages Support Switch statements.

  1. Switch statement
  2. C#
  3. var word = "A";
  4. Switch (word) {
  5. Case "A":
  6. Do something
  7. Break
  8. Case "B":
  9. Do something
  10. Break
  11. Default
  12. Do something
  13. Break
  14. }

  15. Swift
  16. var word = "A"
  17. Switch Word {
  18. Case "A":
  19. Do something
  20. Case "B":
  21. Do something
  22. Default
  23. Do something
  24. }
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.

  1. Switch Case Ranges
  2. C#
  3. switch (i) {
  4. Case 1:
  5. Case 2:
  6. Case 3:
  7. Do something
  8. Break
  9. Case 4:
  10. Do something
  11. Break
  12. Default
  13. Do something
  14. Break
  15. }

  16. Swift
  17. Switch I {
  18. Case 1...3:
  19. Do something
  20. Case 4:
  21. Do something
  22. Default
  23. Do something
  24. }
Copy Code




Functions

WhileFunctions is a much bigger comparisonTo is made, here's a basic example:

    1. Function with Parameter and Return Value
    2. C#
    3. String SayHello (string name) {
    4. Do something
    5. }

    6. Swift
    7. Func SayHello (name:string), String {
    8. Do something
    9. }
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 #

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.