如何在swift 3.0中编写此代码。用于循环
如何在swift 3.0中编写此代码。使用For循环如何在swift 3.0中编写此代码。用于循环,swift,Swift,如何在swift 3.0中编写此代码。使用For循环 for (int index = 0; index < 100; index += (1 + index)) { printf("%d\t",index); } for(int index=0;index
for (int index = 0; index < 100; index += (1 + index)) {
printf("%d\t",index);
}
for(int index=0;index<100;index+=(1+index)){
printf(“%d\t”,索引);
}
您的增量正在增加。由于C样式的for循环不可用,您可以使用如下代码:
var index = 0
while index < 100 {
print("\(index)", terminator: "\t")
index += 1 + index
}
print("")
while index < 100 {
print("\(index)\t")
index += 1 + index
}
var索引=0
而指数<100{
打印(“\(索引)”,终止符:“\t”)
索引+=1+索引
}
打印(“”)
您也可以用函数式编写此代码:
for f in sequence(first: 0,
next: {
$0 + $0 + 1
})
.prefix(while: {$0 < last}) {
print(f, terminator: "\t")
}
print("")
按顺序(第一个:0,
下一步:{
$0 + $0 + 1
})
.prefix(while:{$0(前缀函数需要Swift 3.1)这种
for
循环来自C,与Swift语言的设计和精神背道而驰。这就是为什么它在Swift 3中被删除的原因(你可以找到更多关于删除它的信息)
C-style for循环有三个语句:
首先是初始化语句,在其中设置一个或多个变量。在这种情况下,初始化语句是:
int index = 0
在斯威夫特变成
var index = 0
然后是循环不变量,这是一个条件,在每次循环的开始和结束时必须为真。在这种情况下,循环不变量为:
index < 100
同样,Swift代码与C代码几乎相同
您应该使用while循环,等效的Swift代码如下所示:
var index = 0
while index < 100 {
print("\(index)", terminator: "\t")
index += 1 + index
}
print("")
while index < 100 {
print("\(index)\t")
index += 1 + index
}
而索引<100{
打印(“\(索引)\t”)
索引+=1+索引
}
index+=1+索引
代码虽然有效,但并不常见。您确定要这样做,还是想要更常见的索引+=1
?如果必须使用for循环,可以使用序列,但这将比while循环更冗长、更麻烦:
for index in sequence(first:0, next:{ let index = $0 + $0 + 1; return index < 100 ? index : nil})
{
print("\(index)")
}
顺序索引的(第一个:0,下一个:{let index=$0+$0+1;返回索引<100?索引:nil})
{
打印(“\(索引)”)
}
您还可以使用泛型函数将其推广到任何类型和增量:
func cFor<T>(_ start:T, _ condition:@escaping (T)->Bool, _ increment:@escaping (inout T)->()) -> UnfoldSequence<T, (T?, Bool)>
{
return sequence(first:start, next:{ var next = $0; increment(&next); return condition(next) ? next : nil })
}
for index in cFor(0,{$0<100},{$0 += $0 + 1})
{
print("\(index)")
}
func cFor(uuu开始:T,uu条件:@escaping(T)->Bool,uuu递增:@escaping(inout T)->())->展开序列
{
返回序列(第一个:开始,下一个:{var next=$0;递增(&next);返回条件(下一个)?下一个:nil})
}
对于cFor(0)中的索引,{$0该代码似乎毫无意义。它将产生奇怪的结果。Swift不再有(;;)
的C样式构造,因此您必须使用while循环来构建它。这对我来说闻起来像是一个家庭作业。是否相关:好的、清晰的、逐步的答案。不过有一个小问题。Cprintf()
函数不终止该行,其中Swiftprint()
函数默认情况下会这样做。在我的回答中,我提供了可选的terminator参数,它用一个制表符替换了正常的换行符。您的代码将在新行上显示循环中的每个步骤,这与提供的C代码不同。投票支持正确的翻译,包括使用带terminator的打印。