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

我的代码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." 

该怎么做来解决它?

从Xcode 8 beta 6的发行说明:

  • 已经引入了一个Unsafe[Mutable]RawPointertypes,取代了Unsafe[Mutable]Pointer<Void> 。 从UnsafePointer<T>转换为UnsafePointer<U>已被禁止。 Unsafe[Mutable]RawPointer为无types的内存访问提供了一个API,并提供了一个用于将内存绑定到一个types的API。 绑定内存允许指针types之间的安全转换。 请参阅bindMemory(to:capacity:)withMemoryRebound(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) } } 

更换

 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 } 

Swift 3更新了语法,确切的解决scheme是,

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