我想在Swift 3和Swift 4中使用Swift 2代码:
func getLocalIP() -> String {
var address = "error"
var interfaces : UnsafeMutablePointer<ifaddrs>? = nil
var temp_addr : UnsafeMutablePointer<ifaddrs>? = nil
var success : Int32 = 0
// Retrieve the current interfaces - returns 0 on success.
success = getifaddrs(&interfaces)
if success == 0 {
// Loop through linked list of interfaces.
temp_addr = interfaces
while temp_addr != nil {
if temp_addr?.pointee.ifa_addr.pointee.sa_family == UInt8(AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone.
if String(cString: (temp_addr?.pointee.ifa_name)!) == "en0" {
// Get NSString from C string.
address = String(cString: inet_ntoa(UnsafeMutablePointer<sockaddr_in>((temp_addr?.pointee.ifa_addr)!).pointee.sin_addr))
}
}
temp_addr = temp_addr?.pointee.ifa_next
}
}
// Free memory.
freeifaddrs(interfaces)
return address
}
使用UnsafeMutablePointer时出现错误:
“init”不可用:使用'with内存反弹(到:容量:_)'
1条答案
按热度按时间y1aodyip1#
错误文本准确地说明了错误所在以及您应该执行的操作:您不能再使用指向另一个类型指针来创建
UnsafeMutablePointer
,而必须使用.withMemoryRebound(to:Capacity:_)
方法。在您的情况下,您应该将
就像这样:
或者,这里是函数的完全重写和增强版本: