zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Swift - 条件语句和循环语句

循环 语句 条件 swift
2023-09-11 14:21:23 时间

1.条件语句

先前在可选类型有说过条件语句if else,判断条件最好不加():

var thisStr:String? = ""(这里要注意,“”和nil是两码事)
//看到这里的if,没错,if或者for循环后面的内容不加(),加了也没错,但是并非所有的if或者for循环都可以加,在使用中尽量都不加
if thisStr != nil {
    print(thisStr)
}else{
    print("字符串为 nil")
}

switch语句:不同的是不用加break;

switch expression {
   case expression1  :
      statement(s)
      fallthrough /* 可选 */
   case expression2, expression3  :
      statement(s)
      fallthrough /* 可选 */

   default : /* 可选 */
      statement(s);
}

2.循环语句
for in遍历

//[]不可省,代表字典的意思(猜测)
var intArray:[Int] = [1, 2, 3]
//这里不要()
for index in intArray {
   print( "index 的值为 \(index)")
}

for循环

var intArray:[Int] = [1, 2, 3]
//此处可加(),但是建议不要加,统一起来
for (var index = 0; index < intArray.count; index++) {
   print( "索引 [\(index)] 对应的值为 \(intArray[index])")
}

while语句:

var index = 1
//都是(),统一不加,而且这里加了会报错
while index < 10 
{
   print( "index 的值为 \(index)")
   index = index + 1
}

do…while-> repeat…while

var index = 1

repeat{
    print( "index 的值为 \(index)")
    index = index + 1
}while index < 10

以上就是程序中的几种常用语句,使用方法稍有变化。