美文网首页
04 - 基础篇之循环

04 - 基础篇之循环

作者: flowerflower | 来源:发表于2017-12-13 17:24 被阅读296次

1.循环的介绍

• 在开发中经常会需要循环
• 常见的循环有:for/while/do while.

2.for循环的写法(在3.0之后已经废弃,使用for in)

//报错
/**
Unary operator '++' cannot be applied to an operand of type '@lvalue Int'
C-style for statement has been removed in Swift 3
*/
        for var i = 0 ; i < 10; i++ {
            print(i)
        }

3.for in循环的写法

      for i in 0..<3 {
            print(i) // 0 1 2
        }
        for j in 0...3 {
            print(j) //0 1 2 3
        }
       //特殊写法(如果在for循环中不需要用到下标i)
        for _ in 0..<2 {
            print("hello")  //  hello hello
        }

4.OC和Swift大比拼(for in循环)

OC
格式: for (接收参数 in 取出的参数) {需要执行的语句}
for in含义: 从(in)取出什么给什么, 直到取完为止

for (NSNumber *i  in @[@1, @2, @3]) {
    NSLog(@"%@", i);
}
输出结果:
1
2
3

NSDictionary *dict = @{@"name":@"flower", @"age":@100};
for (NSArray *keys  in dict.allKeys) {
    NSLog(@"%@", keys);
}
输出结果:
name
age
NSDictionary *dict = @{@"name":@"flower", @"age":@100};
for (NSArray *keys  in dict.allValues) {
    NSLog(@"%@", keys);
}
输出结果:
flower
100

Swift:
for in 一般用于遍历区间或者集合

        var sum:Int = 0
        for i in 1...10 { ////会将区间的值依次赋值给i
          sum += i;
        }
        print(sum) // 55
输出结果:55
for dict in ["name": "flower","age":100] as [String: Any] {
            print(dict);
        }
      
输出结果:
  (key: "name", value: "flower")
  (key: "age", value: 100)

for (key, value) in ["name":"flower", "age":100] as [String: Any] {
         print("\(key) = \(value)")
      }
输出结果:
age = 100
name = flower

总结:

for语句
  • 1.for后的圆括号可以省略
  • 2.只能以bool作为条件语句
  • 3.如果只有条指令for后面的大括号不可以省略
  • 4.for后面的三个参数都可以省略, 如果省略循环保持语句, 那么默认为真
for in

一般用于遍历区间或者集合.如果不需要用到下标值,可以使用_来代替

while 和 do while循环

Swift2.0之后变为 repeat while, do用于捕捉异常

  • 1.while后的圆括号可以省略
  • 2.只能以bool作为条件语句
  • 3.如果只有条指令do后面的大括号不可以省略

相关文章

网友评论

      本文标题:04 - 基础篇之循环

      本文链接:https://www.haomeiwen.com/subject/eubnixtx.html