使用 @H_404_2@if@H_404_2@ 和 @H_404_2@switch@H_404_2@ 判断条件,使用@H_404_2@ for-in@H_404_2@ 、@H_404_2@ for @H_404_2@、@H_404_2@ while @H_404_2@和@H_404_2@ do-while@H_404_2@ 处理循环。条件和循环变量的括号可以省略,语句体的大括号是必须的。@H_404_2@
let individualscores = [75,43,103,87,12]@H_404_2@
for score in individualscores {@H_404_2@
} else {@H_404_2@
}@H_404_2@
}@H_404_2@
在@H_404_2@ if @H_404_2@语句中,条件必须是一个布尔表达式 —— 这意味着像@H_404_2@ if score { ... }@H_404_2@ 这样的代码将报错,而不会隐形地与 0 做对比。@H_404_2@
你可以一起使用 @H_404_2@if@H_404_2@ 和@H_404_2@ let@H_404_2@ 来处理条件值缺失的情况。有些变量的值是可选的。一个可选的值如果是一个具体的值或者是 @H_404_2@nil @H_404_2@,那表明这个值缺失。在类型后面加一个@H_404_2@ ?@H_404_2@ 来标记这个变量的值是可选的。@H_404_2@
var optionalString: String? = "Hello"@H_404_2@
optionalString == nil@H_404_2@
@H_404_2@
var optionalName: String? = "John Appleseed"@H_404_2@
var greeting = "Hello! "@H_404_2@
if let name = optionalName {@H_404_2@
greeting = "Hello,\(name)"@H_404_2@
}@H_404_2@
练习:把 optionalName 改成 nil,greeting 会是什么?添加一个 else 语句,当 optionalName 是 nil 时给 greeting 赋一个不同的值。@H_404_2@
@H_404_2@
如果变量的可选值是 @H_404_2@nil@H_404_2@ ,条件会判断为 @H_404_2@false @H_404_2@,并且大括号中的代码会被跳过。如果不是nil,会将值赋给let后面的常量,这样代码块中就可以使用这个值了。@H_404_2@
@H_404_2@
@H_404_2@
使用@H_404_2@switch @H_404_2@支持任意类型的数据以及各种比较操作——不仅仅是整数以及测试相等。@H_404_2@
let vegetable = "red pepper"@H_404_2@
switch vegetable {@H_404_2@
case "celery":@H_404_2@
let vegetableComment = "Add some raisins and make ants on a log."@H_404_2@
case "cucumber","watercress":@H_404_2@
let vegetableComment = "That would make a good tea sandwich."@H_404_2@
case let x where x.hasSuffix("pepper"):@H_404_2@
let vegetableComment = "Is it a spicy \(x)?"@H_404_2@
default:@H_404_2@
let vegetableComment = "Everything tastes good in soup."@H_404_2@
}@H_404_2@
练习:删除 default 语句,看看会有什么错误?@H_404_2@
运行 switch 中匹配到的子句之后,程序会退出switch语句,并不会继续向下运行,所以不需要在每个子句结尾写break。@H_404_2@
@H_404_2@
@H_404_2@
使用 @H_404_2@for-in@H_404_2@ 遍历字典,需要两个变量来表示键和值。@H_404_2@
let interestingNumbers = [@H_404_2@
"Prime": [2,3,5,7,11,13],@H_404_2@
"Fibonacci": [1,1,2,8],@H_404_2@
"Square": [1,4,9,16,25],@H_404_2@
]@H_404_2@
var largest = 0@H_404_2@
for (kind,numbers) in interestingNumbers {@H_404_2@
for number in numbers {@H_404_2@
if number > largest {@H_404_2@
largest = number@H_404_2@
}@H_404_2@
}@H_404_2@
}@H_404_2@
largest@H_404_2@
练习:添加另一个变量来记录哪种类型的数字最大。@H_404_2@
@H_404_2@
@H_404_2@
使用@H_404_2@ while @H_404_2@来重复运行一段代码直到不满足条件。循环条件可以在开头也可以在结尾。@H_404_2@
var n = 2@H_404_2@
while n < 100 {@H_404_2@
n = n * 2@H_404_2@
}@H_404_2@
n@H_404_2@
@H_404_2@
var m = 2@H_404_2@
do {@H_404_2@
m = m * 2@H_404_2@
} while m < 100@H_404_2@
m@H_404_2@
你可以在循环中使用@H_404_2@ ..@H_404_2@ 来表示范围,也可以使用传统的写法,两者是等价的:@H_404_2@
var firstForLoop = 0@H_404_2@
for i in 0..3 {@H_404_2@
firstForLoop += i@H_404_2@
}@H_404_2@
firstForLoop@H_404_2@
@H_404_2@
var secondForLoop = 0@H_404_2@
for var i = 0; i < 3; ++i {@H_404_2@
secondForLoop += 1@H_404_2@
}@H_404_2@
secondForLoop@H_404_2@
使用@H_404_2@ .. @H_404_2@表示的范围不包括上界,如果想包括的话需要使用@H_404_2@ ...@H_404_2@
原文链接:https://www.f2er.com/swift/323146.html