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

后端 未结 3 2136
北恋
北恋 2020-12-13 23:24

My code snipet as follows …:

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        SCNetworkReachabilityCreateWithAddress(nil,         


        
相关标签:
3条回答
  • 2020-12-13 23:44

    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)
        }
    }
    
    0 讨论(0)
  • 2020-12-13 23:44

    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
        }
    
    0 讨论(0)
  • 2020-12-13 23:56

    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 
    }
    
    0 讨论(0)
提交回复
热议问题