swift 循环_Swift进行循环,切换,同时

本文深入探讨Swift中的控制流语句,包括for循环、while循环、repeat-while循环和switch语句。介绍了如何使用这些语句遍历序列、执行条件判断以及实现复杂的逻辑控制。同时,文章还讲解了Swift4中引入的One-SidedRanges特性。
摘要由CSDN通过智能技术生成

swift 循环

In this tutorial, we’ll be looking into the wide variety of statements that Swift has to offer. We’ll be largely covering swift for loop, swift while, repeat-while and switch statements. Open up the playground and let’s dive right in it. Earlier we looked into Swift array. Furthermore we’ll be looking at the newly introduced One Sided Ranges with Swift 4.

在本教程中,我们将研究Swift必须提供的各种语句。 我们将主要介绍swift for loopswift whilerepeat-whileswitch语句。 打开操场,让我们在其中潜水。 之前,我们研究了Swift数组 。 此外,我们将研究带有Swift 4的新推出的One Sided Ranges。

If you’d like to use an online compiler for Swift, go for https://iswift.org/playground.

如果您想为Swift使用在线编译器,请访问https://iswift.org/playground

Swift for循环 (Swift for loop)

To iterate over a sequence without using subscripts (indexes) we use for loop as shown below.

要遍历序列而不使用下标(索引),我们使用for loop ,如下所示。

var numberArray = [2,4,6,8,10]
for number in numberArray {
    print(number)
}

for-in loops using subscripts with lower and upper bounds

使用带有下限和上限的下标的for-in循环

var numberArray = [2,4,6,8,10]
for i in lowerbound...upperbound
{
 //do something
}
//example : 1
var numberArray = [2,4,6,8,10]
for i in 0...4
{
 print(numberArray[i])
}

The array gets iterated from the lowerbound to the upperbound (both inclusive) using closed range operator (...). To iterate with the upper bound not included, we use the half-range operator (..<). An example is given below:

使用封闭范围运算符(...)将数组从下限迭代到上限(包括两端(...) 。 为了不包含上限而进行迭代,我们使用半角运算符(..<) 。 下面是一个示例:

for i in 0..<4
{
 print(numberArray[i]) //doesn't print 10
}

Note: If lowerbound > upperbound there’ll be a crash.
To print the array in reverse order we can use the reversed() function as shown below.

注意 :如果lowerbound > upperbound将会崩溃。
要以相反的顺序打印数组,我们可以使用reversed()函数,如下所示。

for i in (0..<4).reversed()
{
 print(numberArray[i])
}
// the below code will crash
for i in 4..<0 
{
 print(numberArray[i]) 
}

stride is a function from the Swift library that allows us to enter the start value, end value and the offset value to increment by as shown below:

stride是Swift库中的一个函数,可让我们输入起始值,结束值和偏移值以增加如下所示:

//count from 1 to 10 by 1
for i in stride(from: 1, to: 10, by: 1) { 
    print(i)
} 

//count from 1 to 10 by 2
for i in stride(from: 1, to: 10, by: 2) { 
    print(i)
} 
prints:
1
3
5
7
9

Ignoring value from each sequence

忽略每个序列的值

for _ in 1...5 {
    print("Hello World")
}

Underscore effectively gets rid of the value from each sequence. This usage is similar to while loop and can be used for calculating the power of a number as shown below:

下划线有效地消除了每个序列的值。 此用法类似于while循环,可用于计算数字的幂,如下所示:

let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
print("\(base) to the power of \(power) is \(answer)")

While循环 (While loop)

while loops through it’s body of statements until the condition becomes false.

while循环遍历语句的主体,直到条件变为假。

var i = 0
while i <= 5 {
    print(i)
    i = i + 1
}

Note: conditions present in all the control flow statements such as while and for-in loops, if else in Swift, unlike other languages aren’t enclosed in parentheses ().

注意 :所有控制流语句中的条件(例如whilefor-in循环)( if else是Swift的if else存在,与其他语言不同的是,括号()中没有包含这些条件。

repeat-while loops while a condition is met. The difference between a while and a repeat-while loop is that the repeat loop executes the statements present in the body before checking the condition.

满足条件时重复循环。 whilerepeat-while循环之间的区别在于,repeat循环在检查条件之前执行主体中存在的语句。

var i = 5
repeat {
    print(i)
    i = i + 1
} while i < 5

Note: repeat-while loop is similar to the do-while loop in C, JAVA.

注意repeat-while循环类似于C,JAVA中的do-while循环。

切换语句 (Switch statements)

A switch statement considers a value and compares it against several possible matching patterns. An example is given below:

switch语句考虑一个值,并将其与几种可能的匹配模式进行比较。 下面是一个示例:

let character: Character = "a"
switch character {
case "a":
    print("The first letter of the alphabet") //this gets printed.
case "z":
    print("The last letter of the alphabet")
default:
    print("Some other character")
}

Unlike other languages switch statements in swift, finish as soon as the first case is matched. They don’t fallthrough other cases or require an explicit break statement.
To explicitly fallthrough the cases the fallthrough keyword is required as shown under:

与其他语言Swift切换语句不同,第一种情况匹配后立即完成。 它们不会遇到其他情况,也不需要明确的break语句。
要明确发现情况,需要fallthrough关键字,如下所示:

let character: Character = "a"
switch character {
case "a":
    print("The first letter of the alphabet") //this gets printed.
    fallthrough
case "z":
    print("The last letter of the alphabet")//this gets printed too
    fallthrough
default:
    print("Some other character") //this gets printed too
}

Combining multiple cases in switch
Swift allows multiple cases to be appended in switch (separated by commas) as shown below.

组合多个案例
Swift允许将多个案例添加到switch中(用逗号分隔),如下所示。

var myInt = 0

switch myInt
{
case 0, 1, 2:
    print("zero, one or two") //this gets printed.
    
case 3,5,7:
    print("three, five or seven")
    
case 4:
    print("four")
    
default:
    print("Integer out of range")
}

Interval matching in Switch
Values in switch cases can be checked for their inclusion in a certain range as shown below:

交换机中的间隔匹配
可以检查切换案例中的值是否包含在特定范围内,如下所示:

var myInt = 5

switch (myInt)
{
case 0...5:
    print("First half") //this gets printed
    
case 5..<10:
    print("Second half")
    
default:
    print("Out of range")
}

In the above code “First Half” is printed. Though the number 5 exists in both the cases, the first is printed since its met first.
The second case ranges from 5 to 10 where 10 is not inclusive.

在上面的代码中,“上半部分”被打印出来。 尽管在这两种情况下都存在数字5,但是从第一个遇见以来就打印第一个。
第二种情况是5到10,其中不包括10。

Using where statement

使用where语句

var myInt = 5

switch (myInt)
{
case 0...5 where myInt%2==0:
    print("First half only even accepted")
    
case 5..<10:
    print("Second half only odd accepted")
    
default:
    print("Out of range")
}

The where keyword is used to add an additional criteria inside the case.

where关键字用于在案例中添加其他条件。

单面射程 (One-Sided Ranges)

Swift 4 has introduced one-sided ranges wherein the missing range is automatically inferred.
Following example demonstrate the same.

斯威夫特4(Swift 4)引入了一个单边范围,可自动推断出缺失范围。
下面的示例演示相同。

let stringArray = ["How", "you", "doing", "today", "??"]

let lowerHalf = stringArray[..<2] //["How", "you"]
let upperHalf = stringArray[2...] //["doing", "today", "??]

This brings an end to this tutorial. We’ve discussed and implemented all the major control statements.

本教程到此结束。 我们已经讨论并实现了所有主要的控制声明。

翻译自: https://www.journaldev.com/15293/swift-for-loop-switch-while

swift 循环

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值