Swift 3 UnsafePointer($ 0)不再编译在Xcode 8 beta 6中

时间:2016-08-19 19:24:48

标签: swift3 unsafe-pointers xcode8-beta6

我的代码snipet如下......:

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
    }

...不再使用我不理解的以下错误进行编译:

"'init' is unavailable: use 'withMemoryRebound(to:capacity:_)' to temporarily view memory as another layout-compatible type."

如何解决这个问题?

3 个答案:

答案 0 :(得分:125)

来自Xcode 8 beta 6的发行说明:

  
      
  • 引入了Unsafe[Mutable]RawPointer类型,取代Unsafe[Mutable]Pointer<Void>。从UnsafePointer<T>转换为   UnsafePointer<U>已被禁止。 Unsafe[Mutable]RawPointer   为非类型化内存访问提供API,以及用于绑定的API   内存到一个类型。绑定内存允许安全转换   指针类型。见bindMemory(to:capacity:)assumingMemoryBound(to:),   和withMemoryRebound(to:capacity:)。 (SE-0107)
  •   

在您的情况下,您可能需要写下这样的内容:

let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
    $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
        SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
    }
}

答案 1 :(得分:18)

替换

let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
  SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}

guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {

        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {

            SCNetworkReachabilityCreateWithAddress(nil, $0)

        }

    }) else {

        return false
    }

答案 2 :(得分:5)

Swift 3更新了语法,精确解决方案是,

guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
    $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
        zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)} 
} ) else { 
    return false 
}