/*流程控制:循环语句*/
/* swift中的语句是顺序执行的,通过流程控制语句能改变流程导向到其他地方做其他的事情
* swift中的流程控制语句:if、forwhiledo-whileswith
中的循环语句:do-while
*/
//for-in
letindividualscores = [75,43,216)">103,216)">87,216)">12]
varteamscore =0
ifteamscore >50{
teamscore +=3
}else{
teamscore +=1
}
}
//在swift中结合和let,可以方便的处理可控变量(nullable variable),对于空值需要在类声明中添加“?”,这样显式标明该类型可以为空
varoptionalString:String? ="Hello"
optionalString =nil
varoptionalName:"John Appleseed"
vargretting ="Hello!"
ifletname = optionalName{
gretting ="Hello,\(name)"
print(gretting)
}
//for循环(1)
//for in循环:对于数据范围、序列、集合等中的每一个元素都执行一次
//for-condition-increment:一直执行,直到一个特定的条件满足,每一次循环执行,都会增加一次计数
forindexin1...5{
print("\(index) times 5 is\(index *5)")
}
如果不需要序列中的每一个值们可以使用“_”来忽略他,这样仅仅只是用循环本身
letbase =3
letpower =10
varanswer =1
for_1...power{
answer *= base
}
(base) to the power of\(power) is\(answer)")
//for-in遍历数组和字典
letinterestringNumbers = [
"Prime": [2,216)">3,216)">5,216)">7,216)">11,216)">13],
"Fibonacco":[1,216)">8],27)">"Square":[4,216)">9,216)">16,216)">25]
]
varlargest =for(kind,numbers)ininterestringNumbers{
fornumberinnumbers{
ifnumber > largest{
largest = number;
}
}
}
print(largest)
2//swift支持c语言样式的循环
varindex =0;index <3;++index{
"index is\)");
}
以上的循环用表示如下
whileindex <3{
"index2 is\)")
++index;
}
//while循环varn =2
whilen <100{
n = n *2
}
"n is\(n//do-whilevarm =repeat{
m = m *2
}whilem <100
(m)")
原文链接:https://www.f2er.com/swift/324697.html