我正在尝试检查用户是否具有互联网连接,部分过程涉及使用UnsafePointer调用。在Swift 1.x中,我可以使用:
var zeroAddress = sockaddr_in(sin_len: 0,sin_family: 0,sin_port: 0,sin_addr: in_addr(s_addr: 0),sin_zero: (0,0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress){ SCNetworkReachabilityCreateWithAddress(nil,UnsafePointer($0)).takeRetainedValue() }
但是现在用Swift 2,我得到一个错误的说法
Cannot invoke ‘withUnsafePointer’ with an argument list of type ‘(inout sockaddr_in,(_) -> _)’
我看了Xcode的用法,这是:
所以我试过使用
withUnsafePointer(&zeroAddress) {(pointer: UnsafePointer<sockaddr_in>) -> sockaddr_in in SCNetworkReachabilityCreateWithAddress(nil,pointer).takeRetainedValue() }
以及
withUnsafePointer(&zeroAddress) {(pointer: UnsafePointer<sockaddr_in>) -> AnyObject in SCNetworkReachabilityCreateWithAddress(nil,pointer).takeRetainedValue() }
错误信息是误导的,问题在于
SCNetworkReachabilityCreateWithAddress()不返回
不受管理的对象,所以你不能打电话
takeRetainedValue():
原文链接:/swift/320347.htmlSCNetworkReachabilityCreateWithAddress()不返回
不受管理的对象,所以你不能打电话
takeRetainedValue():
var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil,UnsafePointer($0)) }
还要注意,简化了C structs的创建,如struct sockaddr_in推出了Swift 1.2(如果我记得正确的话)。