我的代码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."
如何解决这个问题?
答案 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
}