Fix warning C-style for Statement is deprecated in 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.
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-style for statement has been removed in Swift 3 (Continuos error)
Keeping the index is easy with enumerated
:
for (i, sender) in senderArray.enumerated() {
// Can simply use 'sender' here, no need to index into senderArray.
if sender == userName {
...
// Unchanged lines; 'i' is used as index here.
self.message2Array.append(self.messageArray[i])
self.sender2Array.append(self.senderArray[i])
}
#warning: C-style for statement is deprecated and will be removed in a future version of Swift
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 decrement index
for index in 10.stride(to: 0, by: -1) {
print(index)
}
Or you can use reverse()
like
for index in (0 ..< 10).reverse() { ... }
for float type (there is no need to define any types to index)
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:
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)
}
For decrement index in Swift 3.0
, you can use reversed()
for i in (0 ..< 5).reversed() {
print(i) // 4,3,2,1,0
}
Other then for each
and stride()
, you can use While Loops
var i = 0
while i < 10 {
i += 1
print(i)
}
Repeat-While Loop:
var a = 0
repeat {
a += 1
print(a)
} while a < 10
check out Control flows in The Swift Programming Language Guide
C-style for statement is deprecated and will be removed in a future version of Swift
Here how you rewrite your code with while
cycle:
var viewController: UIViewController? {
var next: UIView? = self.superview
while next != nil {
let responder = next?.nextResponder()
if let vc = responder as? UIViewController {
return vc
}
next = next?.superview
}
return nil
}
c-style for statement deprecated with a twist
Might be best to go with a while loop:
var totalHeight: CGFloat = 0
while totalHeight < 2.0 * Configurations.sharedInstance.heightGame {
// Loop code goes here
totalHeight += backgroundImage.size.height
}
What are the advantages Swift deprecates C-style for statement?
For details, see Swift Evolution - Remove C style for-loops
To quote the reasoning:
- Both
for-in
andstride
provide equivalent behavior using Swift-coherent approaches without being tied to legacy terminology.- There is a distinct expressive disadvantage in using for-loops compared to for-in in succinctness
for-loop
implementations do not lend themselves to use with collections and other core Swift types.- The
for-loop
encourages use of unary incrementors and decrementors, which will be soon removed from the language.- The semi-colon delimited declaration offers a steep learning curve from users arriving from non C-like languages
- If the for-loop did not exist, I doubt it would be considered for inclusion in Swift 3.
In summary: there are better ways (more expressive) than a C-style for-loop
to iterate in Swift.
Some examples:
for-in
over a range:
for i in 0 ..< 10 {
//iterate over 0..9
print("Index: \(i)")
}
for i in (0 ..< 10).reverse() {
//iterate over 9..0
print("Index: \(i)")
}
For arrays (and other sequences) we have many options (the following is not a complete list):
let array = ["item1", "item2", "item3"]
array.forEach {
// iterate over items
print("Item: \($0)")
}
array.reverse().forEach {
// iterate over items in reverse order
print("Item: \($0)")
}
array.enumerate().forEach {
// iterate over items with indices
print("Item: \($1) at index \($0)")
}
array.enumerate().reverse().forEach {
// iterate over items with indices in reverse order
print("Item: \($1) at index \($0)")
}
for index in array.indices {
// iterate using a list of indices
let item = array[index]
print("Item \(item) at index: \(index)")
}
Also note that if you are converting an array to another array, almost always you want to use array.filter
or array.map
or a combination of them.
For all Strideable
types we can use the stride
method to generate indices, for example:
for index in 10.stride(to: 30, by: 5) {
// 10, 15, 20, 25 (not 30)
print("Index: \(index)")
}
for index in 10.stride(through: 30, by: 5) {
// 10, 15, 20, 25, 30
print("Index: \(index)")
}
With arrays we can do:
for index in 0.stride(to: array.count, by: 2) {
// prints only every second item
let item = array[index]
print("Item \(item) at index: \(index)")
}
how to rewrite the following for loop in swift 3 syntax?
for i in stride(from: n-2, through: 0, by: -1) {
}
How to fix C-style for statement?
You could convert the for
loop into a while
loop:
var ptr = ifaddr
while ptr != nil {
// Do stuff
ptr = ptr.memory.ifa_next
}
Related Topics
Can Swift Convert a Class/Struct Data into Dictionary
How to Create Generic Protocols in Swift
Swift 2 ( Executefetchrequest ): Error Handling
Convert a Two Byte Uint8 Array to a Uint16 in Swift
How to Detect a Tap Gesture Location in Swiftui
Closure With Generic Parameters
Arkit - What Do the Different Columns in Transform Matrix Represent
Use Binding≪Int≫ With a Textfield Swiftui
Check If 'Any' Value Is Object
Swift Lazy Instantiating Using Self
Value of Type 'Storagemetadata' Has No Member 'Downloadurl'
Swift - Spritekit Cgpoint Alignment
How to Get Current Language Code With Swift
What Does "@Uiapplicationmain" Mean
Using a Dispatch_Once Singleton Model in Swift