如何在swift 3.0中编写此代码。使用For循环

时间:2017-04-15 00:17:01

标签: swift

如何在swift 3.0中编写此代码。使用For循环?

for (int index = 0; index < 100; index += (1 + index)) {        
    printf("%d\t",index);      
}

3 个答案:

答案 0 :(得分:1)

你的增量正在增加。由于C-style for循环不可用,您可以使用以下代码:

var index = 0
while index < 100 {
  print("\(index)", terminator: "\t")
  index += 1 + index
}
print("")

你也可以用函数式编写这段代码:

for f in sequence(first: 0,
                  next: {
                    $0 + $0 + 1
})
  .prefix(while: {$0 < last}) {
    print(f, terminator: "\t")
}
print("")

(前缀函数需要Swift 3.1)

答案 1 :(得分:1)

这种for循环来自C,与Swift语言的设计和精神背道而驰。这就是为什么它在Swift 3中被淘汰了(你可以找到更多关于它的删除here)。

C-style for循环有三个语句:

首先,有初始化语句,,您可以在其中设置一个或多个变量。在这种情况下,初始化语句是:

int index = 0

在Swift中成为

var index = 0

然后,循环不变,,这是一个条件,必须在每次循环的开始和结束时为真。在这种情况下,循环不变量为:

index < 100

Swift代码与C代码几乎相同。

最后,我称之为更改语句,它会对循环中的某些条件进行更改,需要对其进行评估以查看是否需要通过循环进行另一次传递。在这种情况下,就是这句话:

index += 1 + index

同样,Swift代码与C代码几乎相同。

你应该使用while循环,等效的Swift代码如下所示:

while index < 100 {
  print("\(index)\t")
  index += 1 + index
}

index += 1 + index代码虽然有效但却不常见。你确定你想要那个,或者你想要更常见的index += 1

答案 2 :(得分:0)

如果你必须使用for循环,你可以使用一个序列但是比while循环更冗长和繁琐:

for index in  sequence(first:0, next:{ let index = $0 + $0 + 1; return index < 100 ? index : nil})
{
  print("\(index)")
}

您还可以使用通用函数将此概括为任何类型和增量:

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)")
}