Swift 语言基础(4)-控制流

本文详细介绍了Swift语言中的控制流结构,包括for循环、while循环、条件语句、switch语句等,并通过丰富的示例展示了如何使用这些结构来实现复杂的逻辑判断与控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

for 循环

for ... in ... 循环

 forindexin 1...5{
  println("\(index)times 5 is \(index* 5)")
 }
 // 1 times 5 is 5
 // 2 times 5 is 10
 // 3 times 5 is 15
 // 4 times 5 is 20
 // 5 times 5 is 25


 letbase= 3
 letpower= 10
 varanswer= 1
 for _ in1...power{
 answer*=base
 }
 println("\(base)to the power of \(power)is\(answer)")
 // prints "3 to the power of 10 is 59049"


 letnames= ["Anna","Alex","Brian","Jack"]
 fornamein names {
println("Hello,\(name)!")
 }
 // Hello, Anna!
 // Hello, Alex!
 // Hello, Brian!
 // Hello, Jack!


 letnumberOfLegs= ["spider":8,"ant":6,"cat":4]
 for(animalName,legCount)innumberOfLegs {
     println("\(animalName)s have \(legCount)legs")
 }
 // spiders have 8 legs
 // ants have 6 legs
// cats have 4 legs


 forcharacterin "Hello" {
println(character)
 }
 // H
 // e
 // l
 // l
 // o


For-Condition-Increment

 for varindex= 0;index< 3; ++index{
println("index is\(index)")
 }
 // index is 0
 // index is 1
 // index is 2


 varindex:Int
 forindex= 0;index< 3; ++index{
println("index is\(index)")
 }
// index is 0
 // index is 1
 // index is 2
 println("The loop statements were executed\(index)times")
 // prints "The loop statements were executed 3 times"


while 循环

 varsquare= 0
 vardiceRoll= 0
 whilesquare< finalSquare {
// roll the dice
if++diceRoll==7 { diceRoll = 1 }
// move by the rolled amount
square+=diceRoll
ifsquare< board.count{
// if we're still on the board, move up or down for a snake or a ladder
square+=board[square]
}
  }

println("Game over!")


 do{
// move up or down for a snake or ladder
square+=board[square]
// roll the dice
if++diceRoll==7 { diceRoll = 1 }
 // move by the rolled amount
square+=diceRoll
 }while square < finalSquare
 println("Game over!")


条件语句

if

var temperatureInFahrenheit = 30
 iftemperatureInFahrenheit<= 32 {
println("It's very cold. Consider wearing a scarf.")
 }
 // prints "It's very cold. Consider wearing a scarf."


 temperatureInFahrenheit=40
 if temperatureInFahrenheit<= 32 {
println("It's very cold. Consider wearing a scarf.")
 }else{
println("It's not that cold. Wear a t-shirt.")
 }
 // prints "It's not that cold. Wear a t-shirt."


 temperatureInFahrenheit=90
 if temperatureInFahrenheit<= 32 {
println("It's very cold. Consider wearing a scarf.")
 }else if temperatureInFahrenheit >= 86 {
println("It's really warm. Don't forget to wear sunscreen.")
 }else{
println("It's not that cold. Wear a t-shirt.")
 }
 // prints "It's really warm. Don't forget to wear sunscreen."


temperatureInFahrenheit = 72
 if temperatureInFahrenheit <= 32 {
 println("It's very cold. Consider wearing a scarf.")
 } else if temperatureInFahrenheit >= 86 {
 println("It's really warm. Don't forget to wear sunscreen.")
 }


switch

 let someCharacter: Character = "e"
 switch someCharacter {
 case "a", "e", "i", "o", "u":
 println("\(someCharacter) is a vowel")
 case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
 "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
 println("\(someCharacter) is a consonant")
 default:
 println("\(someCharacter) is not a vowel or a consonant")
} //
prints "e is a vowel"


没有隐性陷入

 let anotherCharacter: Character = "a"
 switch anotherCharacter {
 case "a":
 case "A":
 println("The letter A")
 default:
 println("Not the letter A")
 }
 // this will report a compile-time error


范围匹配

 let count = 3_000_000_000_000
 let countedThings = "stars in the Milky Way"
 var naturalCount: String
 switch count {
 case 0:
naturalCount = "no"
 case 1...3:
naturalCount = "a few"
 case 4...9:
naturalCount = "several"


case 10...99:
naturalCount = "tens of"
case 100...999:
naturalCount = "hundreds of"
case 1000...999_999:
naturalCount = "thousands of"
default:
naturalCount = "millions and millions of"
println("There are \(naturalCount) \(countedThings).")
// prints "There are millions and millions of stars in the Milky Way."


元组匹配

 let somePoint = (1, 1)
 switch somePoint {
 case (0, 0):
println("(0, 0) is at the origin")
 case (_, 0):
println("(\(somePoint.0), 0) is on the x-axis")
 case (0, _):
println("(0, \(somePoint.1)) is on the y-axis")
 case (-2...2, -2...2):
println("(\(somePoint.0), \(somePoint.1)) is inside the box")
default:
println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
} //
prints "(1, 1) is inside the box"


值绑定

 let anotherPoint = (2, 0)
 switch anotherPoint {
 case (let x, 0):
println("on the x-axis with an x value of \(x)")
case (0, let y):
 println("on the y-axis with a y value of \(y)")
 case let (x, y):
  println("somewhere else at (\(x), \(y))")
 }
// prints "on the x-axis with an x value of 2"


附加条件

 let yetAnotherPoint = (1, -1)
 switch yetAnotherPoint {
 case let (x, y) where x == y:
 println("(\(x), \(y)) is on the line x == y")
 case let (x, y) where x == -y:
  println("(\(x), \(y)) is on the line x == -y")
 case let (x, y):
  println("(\(x), \(y)) is just some arbitrary point")
 }
// prints "(1, -1) is on the line x == -y"


控制流变换语句

continue


 let puzzleInput = "great minds think alike"
var puzzleOutput = ""
 for character in puzzleInput {
 switch character {
 case "a", "e", "i", "o", "u", " ":
 continue
 default:
 puzzleOutput += character
 }


break

 let numberSymbol: Character = "" // Simplified Chinese for the number 3
 var possibleIntegerValue: Int?
 switch numberSymbol {
 case "1", "١", "", "๑":
 possibleIntegerValue = 1
 case "2", "٢", "", "๒":
  possibleIntegerValue = 2
 case "3", "٣", "", "๓":
  possibleIntegerValue = 3
case "4", "٤", "", "๔":
possibleIntegerValue = 4
default:
break

if let integerValue = possibleIntegerValue {
println("The integer value of \(numberSymbol) is \(integerValue).")
} else {
println("An integer value could not be found for \(numberSymbol).")
} //
prints "The integer value of is 3."


fallthrough

 let integerToDescribe = 5
 var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
 case 2, 3, 5, 7, 11, 13, 17, 19:
 description += " a prime number, and also"
 fallthrough
 default:
  description += " an integer."
 }
println(description)
// prints "The number 5 is a prime number, and also an integer."


标签语句

gameLoop: while square != finalSquare {
if ++diceRoll == 7 { diceRoll = 1 }
switch square + diceRoll {
case finalSquare:
// diceRoll will move us to the final square, so the game is over
break gameLoop
case let newSquare where newSquare > finalSquare:
// diceRoll will move us beyond the final square, so roll again
continue gameLoop
default:
// this is a valid move, so find out its effect
square += diceRoll
square += board[square]
}

println("Game over!")









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值