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 ...
随机推荐
- LA 3027 Corporative Network 并查集记录点到根的距离
Corporative Network Time Limit: 3000MS Memory Limit: Unknown 64bit IO Format: %lld & %llu [S ...
- UVA12304 2D Geometry 110 in 1! 计算几何
计算几何: 堆几何模版就能够了. . .. Description Problem E 2D Geometry 110 in 1! This is a collection of 110 (in bi ...
- ps、top 、free查看用户资源信息
查看root用户的进程信息. 运行命令: ps -u root 查看oracle用户的进程信息. 运行命令: ps -u oracle 若查看现在的资源占用情况,如何呢? 运行命令: top 可以 ...
- JAVA 保留两位小数的四种方法
import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; publiccl ...
- Nagios+pnp4nagios+rrdtool 安装配置为nagios添加自定义插件(三)
nagios博大精深,可以以shell.perl等语句为nagios写插件,来满足自己监控的需要.本文写mysql中tps.qps的插件,并把收集到的结果以图形形式展现出来,这样输出的结果就有一定的要 ...
- java 字符串 asc 加密解密
package com; public class MD5Test { /** * @param args */ public static void main(String[] args) { Sy ...
- zend studio代码字体修改字体和大小.
第一步:进入设置窗口 windows -> preferences 第二步:进入修改字体的选项卡. General -> Appearance -> Colors and ...
- codeforces293E (树上点分治+树状数组)
和poj1747相比起来,只不过是限制条件多了一维. 而多了这一维,所以需要用树状数组来维护,从而快速得到答案. 因为没注意传进树状数组函数的参数可能是<=0的,导致超时了好久. #pragma ...
- Netty In Action中国版 - 第二章:第一Netty程序
本章介绍 获得Netty4最新的版本号 设置执行环境,以构建和执行netty程序 创建一个基于Netty的server和client 拦截和处理异常 编制和执行Nettyserver和client 本 ...
- Android学习路径(23)应用Fragment建立动态UI——Fragment之间的通信
为了要重用Fragment的UI组件.你应该为它们每个都构建一个完整独立的,模块化的组件来定义他自身的布局和行为. 一旦你定义了这些可重用的Fragments.你能够通过activity关联它们同一时 ...