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 ...
随机推荐
- FZU 1686(重复覆盖)
题目连接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=31370 题意:用尽量少r*c的小矩形覆盖大矩形n*m中的所有1,将 ...
- openwrt教程 第一章 物联网&openwrt开发概述
1.1 我们的宗旨 互联网.移动互联网的时代已经过去,物联网的时代已经来临!2014年,是物联网元年,2016年,物联网将达到高潮!为了迎接该潮流,我们工作室(F403科技创意室:http://f40 ...
- flex 错误信息类型及解决方法
总结一些经常出现的异常信息及处理方法(会一直持续更新): 异常1: 写actionscript3.0时遇到了错误.报错为:Error #2044: 未处理的 ioError:. text=Error ...
- WPF点滴
1 设置窗体的最大化,而且无边框 <Style x:Key="WindowsStyle" TargetType="Window"> <Sett ...
- android IllegalStateException
由于android的线程非安全,直接在子线程中对UI进行更新是不被允许的,同样在常用的 适配器+List<E> 组合中,子线程直接更新与适配器绑定的List,便可能产生IllegalSta ...
- Node.js v0.10.31API手冊-控制台
Node.js v0.10.31API手冊-文件夹 控制台 Object 用于向 stdout 和 stderr 打印字符.类似于大部分 Web 浏览器提供的 console 对象函数,在这里则是输出 ...
- OCP读书笔记(20) - 复制数据库
没有连接到target的复制 将orcl数据库的备份复制为orcl1 一.创建orcl的备份: run{ backup database plus archivelog;} 二.复制数据库为orcl1 ...
- 矩形旋转碰撞,OBB方向包围盒算法实现
怎样进行2D旋转矩形的碰撞检測.能够使用一种叫OBB的检測算法(Oriented bounding box)方向包围盒.这个算法是基于SAT(Separating Axis Theorem)分离轴定律 ...
- MySQL初步研究数据库
我用的是环境Win7.开始学习PHP和MySQL,而买了这<Head First PHP & MySQL>,从能Head First Labs官网获得HeadFirst系列书籍的相 ...
- JavaScript实现的购物车效果-效果好友列表
JavaScript实现的购物车效果.当然,可以在许多地方使用这种效果.朋友的.例如,在选择.人力资源模块,工资的计算,人才选拔等..下面来看一下班似有些车效果图: watermark/2/text/ ...