How to fix C-style for statement?

十年热恋 提交于 2019-12-23 14:23:15

问题


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

回答1:


You could convert the for loop into a while loop:

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



回答2:


Here's a version that worked for me.

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



回答3:


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


来源:https://stackoverflow.com/questions/36153839/how-to-fix-c-style-for-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!