2016-08-19 61 views
58

我的一小段代碼片段如下...:

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

注意http://stackoverflow.com/a/25623647/1187415已經更新爲當前斯威夫特3. –

回答

119

從Xcode的8個β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) 
    } 
} 
+0

是,它爲me..Thanks工作 – TBI

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

斯威夫特3更新了語法,確切的解決方案是,

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