修复警告“C-style for Statement is deprecated"在斯威夫特 3 [英] Fix warning "C-style for Statement is deprecated" in Swift 3

查看:28
本文介绍了修复警告“C-style for Statement is deprecated"在斯威夫特 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将 Xcode 更新到 7.3,现在我对用于创建随机字符串的函数发出警告.

I have update Xcode to 7.3 and now I have a warning to the function that I use to create random strings.

我尝试使用 for (i in 0 ..< len){...} 更改 for 语句,但是,警告变成了错误.

I have tried to change the for statement with for (i in 0 ..< len){...} however, the warning became an error.

如何消除警告?

static func randomStringWithLength (len : Int) -> NSString {
  let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  let randomString : NSMutableString = NSMutableString(capacity: len)

  for (var i=0; i < len; i += 1){ // warning
    let length = UInt32 (letters.length)
    let rand = arc4random_uniform(length)
    randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
  }
  return randomString
}

推荐答案

C-style for 循环已在 Swift 3 中弃用.您可以继续使用它一段时间,但它们肯定会消失未来.

C-style for loop has been deprecated in Swift 3. You can continue using it for a while, but they will certainly disappear in the future.

您可以将循环重写为 Swift 的样式:

You can rewrite your loop to Swift's style:

for i in 0..<len {
    let length = UInt32 (letters.length)
    let rand = arc4random_uniform(length)
    randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}

由于在循环体中根本不使用 i,因此可以将其替换为:

Since you don't use i at all in the loop's body, you can replace it with:

for _ in 0..<len {
    // do stuffs
}

这篇关于修复警告“C-style for Statement is deprecated"在斯威夫特 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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