通过Swift学习Objective-C:条件、流程、集合

上一篇教程简单通过Swift学习Objective-C:变量、类、方法和属性学习了变量、类、方法和属性。这一篇了解Objective-C中的条件,流程和集合的表达方式。

这篇教程适合已学习Swift,至少写个一个demo,想了解一下Objective-C语法的同学们。

控制流程(Control Flow)

IF条件

Swift

1
2
3
4
5
6
7
8
var score = 25
if score > 25 {

}

var aString: String?
if let myString = aString {
}

Swift中用?表示一个变量可以为空值,而if let myString = aString仅在aString存在,及不为空值时候才能运行

Objective-C

1
2
3
4
5
6
7
8
int score = 25;
if (score < 25) {

}

NSString *aString;
if (aString) {
}

Switch选择

Swift

1
2
3
4
5
6
7
8
9
10
var numberOfPeople = 1

switch numberOfPeople {
case 1:
// code for this case
case 2:
// code for this case
default:
// code for this case
}

Objective-C

Objective-C中每一个Case需要以Break; 结尾

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int numberOfPeople = 1;

switch (numberOfPeople)
{
case 1:
// code for this case
break;
case 2:
// code for this case
break;
default:
// code for this case
break;
}

循环

For循环

Swift

1
2
3
4
5
6
7
8
9
or var i = 0; i < 10; i++ {
}

for i in 0..10 {
}

var array = ["item 1", "item 2"]
for item in array {
}

Objective-C

1
2
3
4
5
6
for (int i = 0; i < 10; i++) {
}

NSArray *array = @[@"item 1", @"item 2"];
for (NSString *item in array) {
}

While循环

Swift

1
2
3
4
5
6
7
8
9
var count = 1
while count < 10 {
count++
}

do
{
count++
} while count < 10

Objective-C

1
2
3
4
5
6
7
8
9
int count = 1;
while (count < 10) {
count++;
}

do
{
count++;
} while (count &lt; 10);

集合

声明一个数组

Swift

1
2
var myArray:[String] = [String]()
var myArray2 = ["item 1", "item 2"]

Objective-C

1
2
NSMutableArray *myArray = [[NSMutableArray alloc] init];//创建并初始化
NSMutableArray *myArray2 = [@[@"item 1", @"item 2"] mutableCopy];//直接赋值

向数组添加元素

Swift

1
2
3
4
5
6
myArray[0] = "item 1"

myArray.append("item 3")
myArray += "item 3"

myArray.insert("item 4", atIndex:1)

Objective-C

1
2
3
4
5
myArray[0] = @"item 1";

[myArray addObject:@"item 3"];

[myArray insertObject:@"item 4" atIndex:1];

声明一个词典(Dictionary)

Swift

1
2
3
var myDictionary = Dictionary&lt;String, String&gt;()

var myDictionary2 = ["key":"object", "key2":"object 2"]

Objective-C

1
2
3
NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];

NSMutableDictionary *myDictionary2 = [@{@"key":@"object", @"key2":@"object 2"} mutableCopy];

添加/修改词典元素

Swift

1
2
myDictionary["key3"] = "object 3"
myDictionary["key2"] = "object 4"

Objective-C

1
2
[myDictionary setObject:@"object 3" forKey:@"key3"];
myDictionary[@"key2"] = @"object 4";

下一篇

参考