#warning:不推荐使用 C 风格的 for 语句,并将在未来的 Swift 版本中删除 [英] #warning: C-style for statement is deprecated and will be removed in a future version of Swift

查看:30
本文介绍了#warning:不推荐使用 C 风格的 for 语句,并将在未来的 Swift 版本中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚下载了一个带有 swift 2.2 的新 Xcode (7.3).

I just download a new Xcode (7.3) with swift 2.2.

它有一个警告:

C 风格的 for 语句已被弃用,并将在 Swift 的未来版本中删除.

C-style for statement is deprecated and will be removed in a future version of Swift.

我该如何解决这个警告?

How can I fix this warning?

推荐答案

Removing for init;比较;增加 {} 并轻松删除 ++-- .并使用 Swift 漂亮的 for-in 循环

Removing for init; comparison; increment {} and also remove ++ and -- easily. and use Swift's pretty for-in loop

   // WARNING: C-style for statement is deprecated and will be removed in a future version of Swift
   for var i = 1; i <= 10; i += 1 {
      print("I'm number (i)")
   }

<小时>

Swift 2.2:

   // new swift style works well
   for i in 1...10 {
      print("I'm number (i)")
   }  

<小时>

对于递减索引

  for index in 10.stride(to: 0, by: -1) {
      print(index)
  }

或者你可以像

  for index in (0 ..< 10).reverse() { ... }

<小时>

对于浮点类型(不需要定义任何类型来索引)

 for index in 0.stride(to: 0.6, by: 0.1) {
     print(index)  //0.0 ,0.1, 0.2,0.3,0.4,0.5
 }  

<小时>

Swift 3.0:

Swift3.0 开始,Strideable 上的 stride(to:by:) 方法已被替换为自由函数 stride(from:to:by:)

From Swift3.0, The stride(to:by:) method on Strideable has been replaced with a free function, stride(from:to:by:)

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

对于 Swift 3.0 中的递减索引,可以使用 reversed()

For decrement index in Swift 3.0, you can use reversed()

for i in (0 ..< 5).reversed() {
    print(i) // 4,3,2,1,0
}

其他然后for eachstride(),你可以使用While Loops

Other then for each and stride(), you can use While Loops

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

Repeat-While 循环:

var a = 0
repeat {
   a += 1
   print(a)
} while a < 10

查看 Swift 编程语言指南

这篇关于#warning:不推荐使用 C 风格的 for 语句,并将在未来的 Swift 版本中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆