Swift 3 UnsafePointer($0) no longer compile in Xcode 8 beta 6
Asked Answered
D

3

60

My code snipet as follows …:

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

… does no longer compile with the following error which I don't understand:

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

What to do to fix it?

Drawing answered 19/8, 2016 at 19:24 Comment(1)
Note that https://mcmap.net/q/48801/-how-to-use-scnetworkreachability-in-swift has been updated for the current Swift 3.Paradox
T
126

From the Release Notes of Xcode 8 beta 6:

  • An Unsafe[Mutable]RawPointer type has been introduced, replacing Unsafe[Mutable]Pointer<Void>. Conversion from UnsafePointer<T> to UnsafePointer<U> has been disallowed. Unsafe[Mutable]RawPointer provides an API for untyped memory access, and an API for binding memory to a type. Binding memory allows for safe conversion between pointer types. See bindMemory(to:capacity:), assumingMemoryBound(to:), and withMemoryRebound(to:capacity:). (SE-0107)

In your case, you may need to write something like this:

let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
    $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
        SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
    }
}
Theoretician answered 19/8, 2016 at 21:45 Comment(0)
U
18

Replace

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

with

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

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

            SCNetworkReachabilityCreateWithAddress(nil, $0)

        }

    }) else {

        return false
    }
Utter answered 29/9, 2016 at 8:4 Comment(0)
U
5

Swift 3 updated the syntax,exact solution is,

guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
    $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
        zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)} 
} ) else { 
    return false 
}
Unremitting answered 10/1, 2017 at 12:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.