OC:
int sum = 0;
for (int i = 0; i <= 10; i++) {
sum = i++;
}
NSLog(@"%d", sum);
输出结果:10
int sum = 0;
int i = 0;
for (; i <= 10; i++) {
sum = i++;
}
int i = 0;
for (; i <= 10; i++) {
sum = i++;
}
NSLog(@"%d", sum);
输出结果:10
int sum = 0;
int i = 0;
for (; i <= 10; ) {
sum = i++;
i++;
}
int i = 0;
for (; i <= 10; ) {
sum = i++;
i++;
}
NSLog(@"%d", sum);
输出结果:10
int sum = 0;
int i = 0;
for ( ; ; ) {
sum = i++;
i++;
if (i > 10) {
break;
}
}
int i = 0;
for ( ; ; ) {
sum = i++;
i++;
if (i > 10) {
break;
}
}
NSLog(@"%d", sum);
输出结果:10
int sum = 0;
int i = 0;
for ( ; ; ) {
sum = i++;
i++;
NSLog(@"%d", sum);
int i = 0;
for ( ; ; ) {
sum = i++;
i++;
NSLog(@"%d", sum);
}
输出结果:死循环
如果只有一条指令for后面的大括号可以省略
for后面的三个参数都可以省略, 如果省略循环保持语句, 那么默认为真
Swift:
0.for后的圆括号可以省略
1.只能以bool作为条件语句
2.如果只有条指令for后面的大括号不可以省略
0.for后的圆括号可以省略
1.只能以bool作为条件语句
2.如果只有条指令for后面的大括号不可以省略
3.for后面的三个参数都可以省略, 如果省略循环保持语句, 那么默认为真
var sum:Int = 0
for var i = 0 ; i <= 10 ; i++
{
sum = i++
}
for var i = 0 ; i <= 10 ; i++
{
sum = i++
}
print(sum)
输出结果:10
var sum1:Int = 0
var i1 = 0
for ; i1 <= 10 ; i1++
{
sum1 = i1++
}
var i1 = 0
for ; i1 <= 10 ; i1++
{
sum1 = i1++
}
print(sum1)
输出结果:10
var sum2:Int = 0
var i2 = 0
for ; i2 <= 10;
{
sum2 = i2++
i2++
}
var i2 = 0
for ; i2 <= 10;
{
sum2 = i2++
i2++
}
print(sum2)
输出结果:10
var sum3:Int = 0
var i3 = 0
for ; ;
{
sum3 = i3++
i3++
if i3 > 10
{
break
}
}
var i3 = 0
for ; ;
{
sum3 = i3++
i3++
if i3 > 10
{
break
}
}
print(sum3)
输出结果:10
for in循环
OC:
格式: for (接收参数 in 取出的参数) {需要执行的语句}
for in含义: 从(in)取出什么给什么, 直到取完为止
for (NSNumber *i in @[@1, @2, @3, @4, @5]) {
NSLog(@"%@", i);
NSLog(@"%@", i);
}
输出结果:
2016-04-01 17:17:38.669 OCTest[4599:1510680] 1
2016-04-01 17:17:38.670 OCTest[4599:1510680] 2
2016-04-01 17:17:38.670 OCTest[4599:1510680] 3
2016-04-01 17:17:38.670 OCTest[4599:1510680] 4
2016-04-01 17:17:38.670 OCTest[4599:1510680] 5
NSDictionary *dict = @{@"name":@"QBS", @"age":@100};
for (NSArray *keys in dict.allKeys) {
NSLog(@"%@", keys);
NSLog(@"%@", keys);
}
输出结果:
2016-04-01 17:18:17.419 OCTest[4609:1515258] name
2016-04-01 17:18:17.420 OCTest[4609:1515258] age
NSDictionary *dict = @{@"name":
@“qbs", @"age":@30};
for (NSArray *keys in dict.allValues) {
NSLog(@"%@", keys);
NSLog(@"%@", keys);
}
输出结果:
2016-04-01 17:18:47.592 OCTest[4619:1519194] qbs
2016-04-01 17:18:47.593 OCTest[4619:1519194] 30
Swift:
for in 一般用于遍历区间或者集合
var sum4:Int = 0
for i4 in 1...10 会将区间的值依次赋值给i
{
sum4 += i4;
}
sum4 += i4;
}
print(sum4)
输出结果:
55
for dict in ["name":"QBS", "age":30]
{
print(dict);
print(dict);
}
输出结果:
("age", 30)
("name", QBS)
for (key, value) in ["name":"QBS", "age":30]
{
print("\(key) = \(value)")
print("\(key) = \(value)")
}
输出结果:
age = 30
name = QBS