0

我正在转换Data bytessockaddrsa_family_t

ObjC,如下:

NSData *     hostAddress;
- (sa_family_t)hostAddressFamily {
    sa_family_t     result;

    result = AF_UNSPEC;
    if ( (self.hostAddress != nil) && (self.hostAddress.length >= sizeof(struct sockaddr)) ) {
        result = ((const struct sockaddr *) self.hostAddress.bytes)->sa_family;
    }
    return result;
}

迅速我试图将其转换如下:

var hostAddress:Data?

 private func hostAddressFamily() -> sa_family_t{

        var result: sa_family_t = sa_family_t(AF_UNSPEC)
        if (hostAddress != nil) && ((hostAddress?.count ?? 0) >= MemoryLayout<sockaddr>.size) {

            // Generic parameter 'ContentType' could not be inferred
            self.hostAddress!.withUnsafeBytes({ bytes in
                bytes.withMemoryRebound(to: sockaddr.self, capacity: 1, {sockBytes in
                    result = sockBytes.pointee.sa_family
                })
            })
        }

        return result
    }

Getting error : Generic parameter ‘ContentType’ could not be inferred

4

1 回答 1

1

看签名Data.withUnsafeBytesType

func withUnsafeBytes<ResultType, ContentType>(_ body: (Swift.UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType

ResultType这个方法在and上是通用的ContentType,并且ContentType在闭包体的参数中使用。

编译器想说的是它不知道是什么类型bytes。通常,要修复此类错误,您需要在闭包中注释类型:

data.withUnsafeBytes { (_ bytes: UnsafePointer<...>) -> Void in ... }

此外,您不太可能需要绑定内存两次,因为NSData它是无类型的,并且您已经指定了将其绑定到的类型。


把它们放在一起:

func hostAddressFamily() -> sa_family_t {

  var result = sa_family_t(AF_UNSPEC)

  guard
    let hostAddress = hostAddress,
    hostAddress.count >= MemoryLayout<sockaddr>.size
  else {
    return result
  }

  hostAddress.withUnsafeBytes { (_ bytes: UnsafePointer<sockaddr>) in
    result = bytes.pointee.sa_family
  }

  return result
}
于 2017-08-08T14:14:56.063 回答