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 ...
随机推荐
- 利用try-catch判断变量是已声明未声明还是未赋值
原文 利用try-catch判断变量是已声明未声明还是未赋值 这篇文章主要介绍了利用try-catch判断变量是已声明未赋值还是未声明,需要的朋友可以参考下 目的是如果一个变量是已声明未赋值,就可以直 ...
- Python数据结构之注意事项
1.列表 列表是Python中使用最频繁的数据结构,列表提供很多函数操作,比如下标存取,分片,index,append,remove等等. 例如: list=[1,2,'hello','python ...
- 怎样使用docker不加sudo
有时候发现docker有的指令必须加sudo才干运行,通过下面三步设置便可不加sudo直接运行docker指令: 1. 假设还没有docker group就加入一个: sudo groupadd do ...
- wamp mysql 创建主从数据库
这跟你是不是wmap没有关系的, wamp是一个集成环境,只是一次性帮你创建一个web服务器而已 下面给你些配置 一.登录Master服务器,修改my.ini ,添加如下内容: [wampmysqld ...
- Acquire and Release Semantics
An operation has acquire semantics if other processors will always see its effect before any subsequ ...
- ClientID 获取服务端控件,客户端id的方法
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx. ...
- 不root的情况下 查看App的数据表
一直以来查看sqlite的数据库都须要root才干查看,可是公司的好多測试机root起来比較麻烦~~~ 近期刚好项目上线,略闲, 于是决定写一个libraryproject便于以后调试代码 关键代码例 ...
- 解决vmware卡的要死
如题: 一般而言虚拟机不会卡的.CPU跟随你的操作而增减,内存设置vmware的推荐值就好.遇到卡的情况,检查一下如下情况. 两个方法: 1>内存分配最好是1G,512少了点 2>虚拟机的 ...
- lucas定理解决大组合数取模
LL MyPow(LL a, LL b) { LL ret = ; while (b) { ) ret = ret * a % MOD; a = a * a % MOD; b >>= ; ...
- 尺取法 poj3061 poj3320
尺取法就是反复推进区间的开头和结尾,来求满足条件的最下区间. poj3061 http://poj.org/problem?id=3061 给定一个都是正整数的序列,要我们求总和不小于S的连续子序列的 ...