本文介绍了修复了警告“C语言对于语句已被弃用”在Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我试图用来替换语句中的(我在0 ..< len){...} code>然而,警告成了一个错误。



我怎样才能删除警告?

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

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


解决方案

我还没有找到一种方法来抑制Swift中的单个警告消息。你可以压制一切,这是一个坏主意。



您可以将您的循环重写为Swift风格:

<$ p $ lt;
let length = UInt32(letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat (%C,letters.characterAtIndex(Int(rand)))
}

由于您在循环体内根本不使用 i ,所以您可以将其替换为:

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


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

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

How can I remove the warning?

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
}
解决方案

I haven't found a way to suppress a single warning message in Swift. You can suppress everything, which is a bad idea.

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

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语言对于语句已被弃用”在Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:09