通过Swift学习Objective-C:条件、流程、集合
上一篇教程简单通过Swift学习Objective-C:变量、类、方法和属性学习了变量、类、方法和属性。这一篇了解Objective-C中的条件,流程和集合的表达方式。
这篇教程适合已学习Swift,至少写个一个demo,想了解一下Objective-C语法的同学们。
控制流程(Control Flow)
IF条件
Swift
1 | var score = 25 |
Swift中用?表示一个变量可以为空值,而if let myString = aString
仅在aString存在,及不为空值时候才能运行
Objective-C
1 | int score = 25; |
Switch选择
Swift
1 | var numberOfPeople = 1 |
Objective-C
Objective-C中每一个Case需要以Break; 结尾
1 | int numberOfPeople = 1; |
循环
For循环
Swift
1 | or var i = 0; i < 10; i++ { |
Objective-C
1 | for (int i = 0; i < 10; i++) { |
While循环
Swift
1 | var count = 1 |
Objective-C
1 | int count = 1; |
集合
声明一个数组
Swift
1 | var myArray:[String] = [String]() |
Objective-C
1 | NSMutableArray *myArray = [[NSMutableArray alloc] init];//创建并初始化 |
向数组添加元素
Swift
1 | myArray[0] = "item 1" |
Objective-C
1 | myArray[0] = @"item 1"; |
声明一个词典(Dictionary)
Swift
1 | var myDictionary = Dictionary<String, String>() |
Objective-C
1 | NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init]; |
添加/修改词典元素
Swift
1 | myDictionary["key3"] = "object 3" |
Objective-C
1 | [myDictionary setObject:@"object 3" forKey:@"key3"]; |