Swift和C#的基本语法对比
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#.
itself...
Code
Comments
familiar C-style comments.
- // code comment
- /* multi line
- code comment */
复制代码
Declaring Constants and Variables
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.
- // Declare Constant
- // C#
- const int legalAge = 18;
- // Swift
- let legalAge = 18
- // Declare Variable
- // C#
- var legalAge = 18;
- // Swift
- var legalAge = 18
复制代码
assign a value to the variable you may need to explicitly specify the type of
the variable.
- // Type Annotation
- //C#
- string firstName;
- // Swift
- var firstName: String
复制代码
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
names. Basically, you could use Emoticons or other non-ASCII characters as
variable names if you want, but who does that
anyway?
Integer Bounds
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
复制代码
Type Inference
the compiler is able to detect what type the declared variable 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
复制代码
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
- // String Comparison
- // C#
- var a = "One";
- var b = "One";
- if (a == b) {
- // both variables are considered equal
- }
- // Swift
- var a = "One"
- var b = "One"
- if a == b {
- // both variables are considered equal
- }
复制代码
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
- }
复制代码
required with IF statements in Swift.
String Upper or Lower Case
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
复制代码
Declaring Arrays
single line of code.
- // Declare Arrays on single line
- // String Array
- // C#
- var arr = new string[] { "One", "Two" };
- // Swift
- var arr = ["One", "Two"]
- // Integer Array
- // C#
- var arr = new int[] { 1, 2 };
- // Swift
- var arr = [1, 2];
复制代码
Working with Arrays
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)
复制代码
Declaring Dictionaries
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"]
复制代码
Working with Dictionaries
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")
复制代码
For Loops
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.
- // 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
- }
复制代码
of shorthand it uses for it's definition.
Conditional Statements
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
- }
复制代码
Switch Statement
- // 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
- }
复制代码
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.
is ranges within the Case statements. This is 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
- }
复制代码
Functions
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
- }
复制代码
much more depth on Functions; as that is a much bigger comparison that could fit
into this post.
Conclusion
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.
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.)
language on Apple's site at the following links:
Swift和C#的基本语法对比的更多相关文章
- Java, C#, Swift语法对比速查表
原文:Java, C#, Swift语法对比速查表 Java 8 C# 6 Swift 变量 类型 变量名; 类型 变量名; var 变量名 : 类型; 变量(类型推断) N/A var 变量名= ...
- 快看Sample代码,速学Swift语言(1)-语法速览
Swift是苹果推出的一个比较新的语言,它除了借鉴语言如C#.Java等内容外,好像还采用了很多JavaScript脚本里面的一些脚本语法,用起来感觉非常棒,作为一个使用C#多年的技术控,对这种比较超 ...
- 【Swfit】Swift与OC两种语法写单例的区别
Swift与OC两种语法写单例的区别 例如写一个NetworkTools的单例 (1)OC写单例 + (instancetype)sharedNetworkTools { static id inst ...
- 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.单继 ...
- Swift与C#的基础语法比较
背景: 这两天不小心看了一下Swift的基础语法,感觉既然看了,还是写一下笔记,留个痕迹~ 总体而言,感觉Swift是一种前后端多种语言混合的产物~~~ 做为一名.NET阵营人士,少少多多总喜欢通过对 ...
- MongoDB命令及SQL语法对比
mongodb与mysql命令对比 传统的关系数据库一般由数据库(database).表(table).记录(record)三个层次概念组成,MongoDB是由数据库(database).集合(col ...
- MongoDB(五)mongo语法和mysql语法对比学习
我们总是在对比中看到自己的优点和缺点,对于mongodb来说也是一样,对比学习让我们尽快的掌握关于mongodb的基础知识. mongodb与MySQL命令对比 关系型数据库一般是由数据库(datab ...
- Swift超详细的基础语法-结构体,结构体构造器,定义成员方法, 值类型, 扩充函数
知识点 基本概念 结构体的基本使用 结构体构造器(构造函数/构造方法) 结构体扩充函数(方法), 又称成员方法 结构体是值类型 1. 基本概念 1.1 概念介绍 结构体(struct)是由一系列具有相 ...
- Swift - 35 - 使用闭包简化语法
//: Playground - noun: a place where people can play import UIKit // 初始化一个整数数组 var arr = [1, 3, 5, 7 ...
随机推荐
- codeforces 112APetya and Strings(字符串水题)
A. Petya and Strings 点击打开题目 time limit per test 2 seconds memory limit per test 256 megabytes input ...
- LeetCode——Valid Sudoku
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be ...
- Conversion to Dalvik format failed with error 1
主要和添�的第三方的包有关系. ======================================= 出现,Conversion to Dalvik format failed with e ...
- NodeJS - Express4.0错误:Cannot read property &#39;Store&#39; of undefined
Express在使用mongodb的时候app配置出错 //settings.js module.exports={ cookieSecret:"xxxx", db:"d ...
- 使用scipy进行聚类
近期做图像的时候,突然有个idea,须要进行聚类,事实上算法非常easy,可是当时非常急.就直接使用了scipy的cluster. 使用起来事实上非常easy,可是中文的文章非常少,所以就简单的介绍一 ...
- 23设计模式(3):Abstract Factory模式
定义:要创建一组相关或依赖对象提供一个接口,而你并不需要指定其具体类别. 类型:创建一个类模型 类图: 抽象工厂模式与工厂方法模式的差别 抽象工厂模式是工厂方法模式的升级版本号,他用来创建一组相关或者 ...
- Linux如何用QQ?Linux下QQ使用的几种方案
在linux下如何使用QQ?在ubuntu11.10中如何使用QQ?或许有初涉linux的人这样问,我们可以看看ubuntusoft总结出来的几种在linux系统下用QQ的方法.前面的几种主要的方法都 ...
- 挺好用的SQLSERVER数据库自动备份工具SQLBackupAndFTP(功能全面)
原文:挺好用的SQLSERVER数据库自动备份工具SQLBackupAndFTP(功能全面) 挺好用的SQLSERVER数据库自动备份工具SQLBackupAndFTP(功能全面) 这个工具主要就是自 ...
- json2.js参考
json2.js使用參考 json2.js提供了json的序列化和反序列化方法,能够将一个json对象转换成json字符串,也能够将一个json字符串转换成一个json对象. <html> ...
- HDU 3681 BFS&像缩进DP&二分法
N*M矩阵.从F出发点.走完全部Y点.每个人格开支1电源点,去G点,电池充满,D无法访问.最小的开始问什么时候满负荷可以去完全部Y.Y和G总共高达15一 第一BFS所有的F.Y.G之间的最短距离. 然 ...