Recently, Apple announced and released a beta version of the new Swift programming language for 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 has 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 that this post is not supposed to be an
Apple vs Microsoft post. There are a lot of developers that use C# every day and
the purpose of this post is to help them understand what Swift offers at a
language level compared to C#. And, before you start the "apples and oranges"
arguments, it's worth pointing out that using Xamarinyou 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 */

复制代码

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 infer (or detect) the type by evaluating the assignment of the
variable. While C# is slightly more verbose when declaring constants; both
languages are 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

复制代码

While type inference is nice, but when you don't immediately
assign a value to the variable you may need to explicitly specify the type of
the variable.
  1. // Type Annotation
  2. //C#
  3. string firstName;
  4. // Swift
  5. var firstName: String

复制代码

You may 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 have multiple code statements on
the same line.

Variable Names and
Unicode

Both languages support the use of Unicode characters as variable
names. Basically, you could use Emoticons or other non-ASCII characters as
variable names if you want, but who does that
anyway?

Integer Bounds

Both languages have 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

复制代码

Type Inference

Both languages, as mentioned above, support type inference where
the compiler is able to detect what type the declared variable 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

复制代码

Also in the above type inference example you'll notice that when
you declare a variable and immediately assign a value that is the result of 2
other variables it will still infer the type.

String Comparison

Both have 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 are considered equal
  7. }
  8. // Swift
  9. var a = "One"
  10. var b = "One"
  11. if a == b {
  12. // both variables are considered equal
  13. }

复制代码

The both also have 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. }

复制代码

You may notice from the above example that parenthesis are 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

复制代码

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", "Two" };
  5. // Swift
  6. var arr = ["One", "Two"]
  7. // Integer Array
  8. // C#
  9. var arr = new int[] { 1, 2 };
  10. // Swift
  11. var arr = [1, 2];

复制代码

Working with Arrays

Working with Arrays have 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)

复制代码

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"]

复制代码

Working with Dictionaries

Working with Dictionaries have 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")

复制代码

For Loops

The above examples for Arrays and Dictionaries already showed
examples of using a For-In loop to iterate through the items in those
collections. Here are 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. }

复制代码

The range example of Swift is 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. }

复制代码

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. }

复制代码

Switch statements are rather similar in both languages except
that in Swift case statements don't automatically pass on to the next like in
C#. As a result C# requires the use of the break keywords to exit the Switch
statement, unless you want to fall through to the next case. While in Swift you
must use the "fallthrough" keyword to tell it to pass on through to the next
case statement. More information on this can be found in the Swift
documentation.
An additional feature that Swift supports with Switch statements
is ranges within the Case statements. This is 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. }

复制代码

Functions

While Functions are a much bigger comparison to be 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. }

复制代码

The post Basic Comparison of Functions in C# and Swift goes into
much more depth on Functions; as that is a much bigger comparison that could fit
into this post.

Conclusion

This concludes my basic comparison of C# and Apple Swift
programming languages. The two languages are rather similar in many respects; at
least in what I've compared thus far. More language feature comparisons will
have to wait for future posts.
One of the bigger differences that's worth pointing out
explicitly is the difference in how each language handles Array's. Arrays in
Swift are extremely similar to the List<> class in C#; which is what 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:

Swift和C#的基本语法对比的更多相关文章

  1. Java, C#, Swift语法对比速查表

    原文:Java, C#, Swift语法对比速查表   Java 8 C# 6 Swift 变量 类型 变量名; 类型 变量名; var 变量名 : 类型; 变量(类型推断) N/A var 变量名= ...

  2. 快看Sample代码,速学Swift语言(1)-语法速览

    Swift是苹果推出的一个比较新的语言,它除了借鉴语言如C#.Java等内容外,好像还采用了很多JavaScript脚本里面的一些脚本语法,用起来感觉非常棒,作为一个使用C#多年的技术控,对这种比较超 ...

  3. 【Swfit】Swift与OC两种语法写单例的区别

    Swift与OC两种语法写单例的区别 例如写一个NetworkTools的单例 (1)OC写单例 + (instancetype)sharedNetworkTools { static id inst ...

  4. Python3 与 C# 面向对象之~继承与多态 Python3 与 C# 面向对象之~封装 Python3 与 NetCore 基础语法对比(Function专栏) [C#]C#时间日期操作 [C#]C#中字符串的操作 [ASP.NET]NTKO插件使用常见问题 我对C#的认知。

    Python3 与 C# 面向对象之-继承与多态   文章汇总:https://www.cnblogs.com/dotnetcrazy/p/9160514.html 目录: 2.继承 ¶ 2.1.单继 ...

  5. Swift与C#的基础语法比较

    背景: 这两天不小心看了一下Swift的基础语法,感觉既然看了,还是写一下笔记,留个痕迹~ 总体而言,感觉Swift是一种前后端多种语言混合的产物~~~ 做为一名.NET阵营人士,少少多多总喜欢通过对 ...

  6. MongoDB命令及SQL语法对比

    mongodb与mysql命令对比 传统的关系数据库一般由数据库(database).表(table).记录(record)三个层次概念组成,MongoDB是由数据库(database).集合(col ...

  7. MongoDB(五)mongo语法和mysql语法对比学习

    我们总是在对比中看到自己的优点和缺点,对于mongodb来说也是一样,对比学习让我们尽快的掌握关于mongodb的基础知识. mongodb与MySQL命令对比 关系型数据库一般是由数据库(datab ...

  8. Swift超详细的基础语法-结构体,结构体构造器,定义成员方法, 值类型, 扩充函数

    知识点 基本概念 结构体的基本使用 结构体构造器(构造函数/构造方法) 结构体扩充函数(方法), 又称成员方法 结构体是值类型 1. 基本概念 1.1 概念介绍 结构体(struct)是由一系列具有相 ...

  9. Swift - 35 - 使用闭包简化语法

    //: Playground - noun: a place where people can play import UIKit // 初始化一个整数数组 var arr = [1, 3, 5, 7 ...

随机推荐

  1. 不可不知的DIP、IoC、DI以及IoC容器

    面向对象设计(OOD)有助于我们开发出高性能.易扩展以及易复用的程序.当中.OOD有一个重要的思想那就是依赖倒置原则(DIP),并由此引申出IoC.DI以及Ioc容器等概念. 本文首先用实例阐述四个概 ...

  2. 【Java 它 JVM】对象的创建过程

    虚拟机会new 指令: 1.检查指令的参数可在对类的符号引用的恒定饮食定位,并检查是否已装上代表这个类的符号引用.分析和初始化.假设没有.您必须运行相应的类加载过程. 2.类加载通过审查,虚拟机将分配 ...

  3. java中常用的字符串的截取方法

    java中常用的字符串的截取方法   1.length() 字符串的长度 例:char chars[]={'a','b'.'c'}; String s=new String(chars); int l ...

  4. poj3264(线段树区间求最值)

    题目连接:http://poj.org/problem?id=3264 题意:给定Q(1<=Q<=200000)个数A1,A2,```,AQ,多次求任一区间Ai-Aj中最大数和最小数的差. ...

  5. My97 DatePicker

    支持日期以及时分秒的选择, 国人开发, 还不错! 官网: http://www.my97.net/

  6. js检测浏览器中是否安装了flash播放插件

    这两天工作中需要在网页中嵌入flash小游戏,我使用的是swfobject.js version:1.5.其他方面都很好,唯独版本检测这里一直没有搞通,后来实在无奈之下,改用js来检测浏览器的flas ...

  7. .Net程序猿玩转Android开发---(7)相对布局RelativeLayout

                 相对布局RelativeLayout是Android布局中一个比較经常使用的控件,使用该控件能够布局出适合各种屏幕分辨率的布局,RelativeLayout採用相对位置进行 ...

  8. Android Handler Message总结一下

    当应用程序启动时,会开启一个主线程(也就是UI线程).由她来管理UI.监听用户点击.来响应用户并分发事件等.所以一般在主线程中不要运行比較耗时的操作,如联网下载数据等,否则出现ANR错误.所以就将这些 ...

  9. 如何使用 yum 安装/更新/移除 软件

    如何使用 yum 安装/更新/移除 软件 一. 建立仓库(repository)和源 a) 拷贝所以相关rpm包到某个目录 b) 执行createrepo  /目录/目录/目录/目录   注意:b)中 ...

  10. LNMP 免安装包

    LNMP(Linux-Nginx-Mysql-PHP)可爱的黄金搭档,不过配置并不轻易,而我平常用于测试环境又经常用到,所以打包了这么一个免安装的LNMP包,内置常用库和模块,以及基本的优化设置,这样 ...