Ramis
Ramis

Reputation: 16609

How to fix C-style for statement?

What is right way to fix C-style for statement for the code which is posted below?

Currently I am getting this warring:

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

var ifaddr : UnsafeMutablePointer<ifaddrs> = nil
if getifaddrs(&ifaddr) == 0 {
    // Warning
    for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next) {
        // Do some stuff...
    }
}

Upvotes: 4

Views: 417

Answers (3)

Martin R
Martin R

Reputation: 539955

As of Swift 3 you can use sequence for generalized loops, such as traversing a "linked list". Here:

var ifaddr : UnsafeMutablePointer<ifaddrs>?
if getifaddrs(&ifaddr) == 0 {
    if let firstAddr = ifaddr {
        for ptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
            // ...
        }
    }
    freeifaddrs(ifaddr)
}

Upvotes: 0

Telstar
Telstar

Reputation: 143

Here's a version that worked for me.

var ptr = ifaddr
repeat {
   ptr = ptr.memory.ifa_next
   if ptr != nil {
      ...
   }
} while ptr != nil

Upvotes: 3

JAL
JAL

Reputation: 42459

You could convert the for loop into a while loop:

var ptr = ifaddr
while ptr != nil {
    // Do stuff
    ptr = ptr.memory.ifa_next
}

Upvotes: 7

Related Questions