![](https://img.haomeiwen.com/i5956443/478e132e30e2e20e.jpg)
分类 | C/C++语言 | swift | 说明 |
---|---|---|---|
常量 | Const int a = 1234; |
Let a = 1234 | 1. c/c++有明确的类型,而swift都是隐式类型 2. c/c++以;为隔符,而 swift是以回车换行为分隔符。 |
变量 | Int a = 1234; | Var a = 1234 | 变量swift也是不需要指定类型的。 |
If语句 | If(a>5){ ... }else{ ... } |
if score > 50 { teamScore += 3 } else { teamScore += 15. } |
在 c/c++中 if 语句后面需要 (),而 switf则不需要。 |
For 语句 | For(int i=0; i<10; i++){ ... } |
For a in list { ... } |
1. Swift好像不爱用 (),在 for 语句中也不使用它。 2. Swift 使用 in 来遍历,这基本是现代语言的常用方式了。 |
While语句 | While (n < 100){ } |
While n<100 { n *= 22 } |
1. 同样不使用() |
Switch…case | Switch(state){ Case 1: … Break; Case 2: … Break; Default: } |
Switch stat { Case 1: … Case 2: … Default: } |
1. 同样,swift在 switch 中也不用 () 2. Break也省掉了,这是写c/c++特别容易出错的地方。 |
函数 | Int myfunc(int a){ Printf("the arg is %d", a); Return a; } Int aa = myfunc(a); |
Func myfunc( a:int )->int{ Print("the arg is (a)"); Return a } Var aa = myfunc(a) |
1. c/c++函数返回值在前面,而 swift的返回值在后面,而且有 ->关键字。 2. 在定义函数时,swift也躲不开()了。 3. c/c++形参的格式是 类型 形参变量,而swift是形参变量:类型 4. swift定义函数是要用 func 关键字,而 c/c++不需要。 |
函数多返回值 | 无 | func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) { var min = scores[0] var max = scores[0] var sum = 0 for score in scores { if score > max { max = score } else if score < min { min = score} sum += score } return (min, max, sum) } |
Swift函数可以返回多个值,而 c/c++不行。这点比较特殊。 |
类 | Class A{ Public: A(){ } ~A(){ } Public: … Private: … }; |
Class A{ Var a Func getA() -> int{ Return a } Init(){ } } |
1. 在c/c++中,有 public/protected/private的权限防问,而swift没有这个限制。 2. 在c/c++中的构造函数与类名相同,而在 swift里是 init。 3. 在c/c++中类定义完扣有 ;, 而swift里没有。 |
类的继承 | Class A: public B{ } |
Class A: B{ Override func () ->int{ } } |
1.区别在于没有 public/protected之类的访问权限限制。 2. 方法重载在c/c++里是自动的,而在 swift里需要加 override关键字。 |
类的属性 | Class EquilateralTriangle{ Private: Double perimeter; Public: Void setPerimeter(Double p){ Perimeter = p; } Double getPerimeter(){ Return perimeter; } } |
class EquilateralTriangle: NamedShape { var sideLength: Double = 0.0 init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } var perimeter: Double { get { return 3.0 * sideLength } set { sideLength = newValue / 3.0 } } override func simpleDescription() -> String { return "An equilateral triangle with sides of length (sideLength)." } } var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") print(triangle.perimeter) triangle.perimeter = 9.9 print(triangle.sideLength) |
在 c/c++中,要想访问私有的成员变量,必须通过在类中定义的setter/getter公有方面才行。 而在swift中,可以对某个成员变量设置 get/set 属性,而调用的时候,可以通过"."来访问。 |
网友评论