欢迎加QQ群讨论:157672725
一、条件语句
if语句
1.在if语句中,条件必须是一个布尔表达式【if(0)这样的写法是错的,因为0不是布尔表达式】
2.if( )的括号可写可不写
var score = 100
var totalscore = 0
if score > 100 {
totalscore += 2
} else {
totalscore += 1
}
print(totalscore)
3.if和let处理值缺失的情况【处理可选值】
var optionalStr: String? = "opValue"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello,\(name)"
}
如果 var optionalStr: String? 则 if的条件将会不成立。
switch语句
1.switch支持任意类型的数据以及各种比较操作——不仅仅是整数以及测试相等
2.swicth必须有default的情况,否则报错
3.case可以多值判断用,隔开 (如 :case “bbb”,”ccc”)
4.声明let可用于匹配某部分固定值的模式
5.switch匹配到子句之后,程序会退出switch语句,并不会继续向下运行,所以不需要在每个子句结尾写break
let strSwitch = "bbb"
switch strSwitch {
case "aaa":
let str = "aaaaaaaa"
print(str)
case "bbb","ccc":
let str = "bbbbbbbb/ccccccc"
print(str)
case let x where x.hasSuffix("a"):
let str = "Is it a spicy \(x)?"
print(str)
default:
let str = "default"
print(str)
}
输出:bbbbbbbb/ccccccc
二、循环语句
for语句
1.使用var声明i来循环
for var i=0;i<4;i++{ forTest++; }
print(forTest)
输出: 4
2.可以使用 for in 来遍历
var firstForLoop = 0
for i in 0..<4 {
firstForLoop += i
}
print(firstForLoop)
输出: 6
print("\n")
var secondForLoop = 0
for var i = 0; i < 4; ++i {
secondForLoop += i
}
print(secondForLoop)
输出: 6
3…<创建的范围不包含上界,…包含上界
var firstForLoop = 0
for i in 0...4 {
firstForLoop += i
}
print(firstForLoop)
print("\n")
输出: 10
4.for用于遍历字典【需要两个变量来表示每个键值对】
let interestingNumbers = [
"Prime": [2,3,5,7,11,13],"Fibonacci": [1,1,2,8],"Square": [1,4,9,16,25],]
var largest = 0
for (kind,numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
输出: 25
while语句
- 同样的条件部分的括号可不写
var n = 1
while n < 10 {
n*=2
}
print(n)
输出: 16