//Swift
let username = "twostraws"
print("Username is (username)")
控制流
检查状态
//Objective-C
NSInteger result = 86;
if (result >= 85) {
NSLog(@"You passed the test!");
} else {
NSLog(@"Please try again.");
}
//Swift
let result = 86
if result >= 85 {
print("You passed the test!")
} else {
print("Please try again.")
}
循环一定次数
//Objective-C
for (NSInteger i = 0; i < 100; ++i) {
NSLog(@"This will be printed 100 times.");
}
//Swift
for _ in 0 ..< 100 {
print("This will be printed 100 times.")
}
在数组中循环
//Objective-C
NSArray *companies = @[@"Apple", @"Facebook", @"Twitter"];
for (NSString *name in companies) {
NSLog(@"%@ is a well-known tech company.", name);
}
//Swift
let companies = ["Apple", "Facebook", "Twitter"]
for name in companies {
print("(name) is a well-known tech company.")
}
数值切换
//Objective-C
NSInteger rating = 8;
switch (rating) {
case 0 ... 3:
NSLog(@"Awful");
break;
case 4 ... 7:
NSLog(@"OK");
break;
case 8 ... 10:
NSLog(@"Good");
break;
default:
NSLog(@"Invalid rating.");
}
//很多人不知道Objective-C有范围支持,所以你也许看到二选一的语法
//Swift
let rating = 8
switch rating {
case 0...3:
print("Awful")
case 4...7:
print("OK")
case 8...10:
print("Good")
default:
print("Invalid rating.")
}
//Swift不会fall through案例,除非你使用fallthrough关键字
函数
不接收参数也没有返回的函数








