对比一下两种语言的语法,以防止自己搞混。以便于自己记忆。
肯定是不全的,随时增删改查。
在线文档; https://devdocs.io/
概念 | swift5 | C++ |
打印 | print( "Hello World") | printf("Hello World"); |
关键字, 数据类型 | var let enum : Optional struct : Bool、Int、Float、Double、Character, String、Array、Dictionary、Set class :
Void
Int8、Int16、Int32、Int64、UInt8、UInt16、UInt32、UInt64 |
asm auto bool break case |
变量 | var value = 10 //整形 自动识别类型
var value = "hello world" //字符串
var value = [1,3,5,7,9] //数组
var dic = ["length":1, "width":2, "height":3] //字典
var stu = ("0001","man",90,"高一9班",170,120) | int value = 10; float value = 10.0
//字符串 const char *st = "The expense of spirit\n";
int ia[10]; //数组
int ia[] = { 0, 1, 2 }; //数组 |
常量 | let value = 10
let value: Float = 10.5 //指定类型 | // 缓冲区大小 const int bufSize = 512 |
if-else | let age = 30 if age > 100 { print("died") }else if age > 60 { print("old") }else if age >= 30 { print("married") }else{ print("happy") } | int age = 30; if (age > 100) { printf("died"); }else if( age > 60) { printf("old"); }else if( age >= 30 ){ printf("married"); }else{ printf("happy"); } |
while | var num = 3
//repeat-while var num = 3 | int num = 3;
/do-while int num = 3; |
for | //i 默认是let , 也可以声明为var for i in 1...5{
for i in 1...5 where i != 3 {
let names = ["hello","world","look"] | for(int i = 1; i <=5; ++i){ printf("%d",i); } |
switch | ||
函数 | func getPi() -> Double { func sum(v1 : Int, v2: Int) -> Int{ print(getPi()) | double getPi() int sum( int v1, int v2) printf("%.6f",getPi()); |
输入输出参数 | func swapValues(_ v1: inout Int, _ v2: inout Int) { var v1 = 3 | 通过 指针 或者 引用 |
枚举 | enum Direction : Int{ case north case south case east case west } print(Direction.north) print(Direction.north.rawValue) | enum Direction{
printf("%d",north); |
获取占用的字节大小 | // 8, 分配占用的空间大小 print(MemoryLayout<Int>.stride)
// 8, 实际用到的空间大小
// 8, 对齐参数
var ret = "helloworld" | //4 printf("%d",sizeof(int));
|
可选项 | ||
struct | struct Date{ var date = Date(year:2019, month:11, day:21)
// struct Date{ var date = Date(year:2017, month:11, day:21)
| |
class | class Size{ var size = Size() | |
闭包表达式 | ||
存储属性 和 计算属性 | struct Rect{ } var rect = Rect(width:5) rect.area = 20 | |
类型属性 | struct Car{ init(){ var car1 = Car() print(Car.count) | |
继承 | //值类型(枚举、结构体)不支持继承,只有类支持继承 class Animal { var erha = ErHa() | |
重写实例方法 | class Animal{ class Cat : Animal{ var animal = Animal() animal = Cat() | |
协议(Protocol) | ||
Any is | protocol Runnable { func run() } class Person{} class Student : Person, Runnable { func run(){ var stu : Any = 10
| |
局部作用域 | do{ //.... } | |