objective-c – 如何在Swift中执行memcmp()?

我正在尝试将我的一些代码从Objective-C转换为
Swift.我遇到问题的一种方法是将CBUUID与UInt16进行比较.这在Objective-C中相当简单,但我很难想出一个在Swift中做到这一点的好方法.

这是Objective-C版本:

/*
 *  @method compareCBUUIDToInt
 *
 *  @param UUID1 UUID 1 to compare
 *  @param UUID2 UInt16 UUID 2 to compare
 *
 *  @returns 1 (equal) 0 (not equal)
 *
 *  @discussion compareCBUUIDToInt compares a CBUUID to a UInt16 representation of a UUID and returns 1
 *  if they are equal and 0 if they are not
 *
 */
-(int) compareCBUUIDToInt:(CBUUID *)UUID1 UUID2:(UInt16)UUID2 {
    char b1[16];
    [UUID1.data getBytes:b1];
    UInt16 b2 = [self swap:UUID2];
    if (memcmp(b1, (char *)&b2, 2) == 0) return 1;
    else return 0;
}

我在Swift中的这个方法的(未经测试的)版本变得更加复杂,我希望我只是缺少一些更好的方法来使用该语言:

func compareCBUUID(CBUUID1: CBUUID, toInt CBUUID2: UInt16) -> Int {
    let uuid1data = CBUUID1.data
    let uuid1count = uuid1data.length / sizeof(UInt8)
    var uuid1array = [UInt8](count: uuid1count, repeatedValue: 0)
    uuid1data.getBytes(&uuid1array, length: uuid1count * sizeof(UInt8))

    // @todo there's gotta be a better way to do this
    let b2: UInt16 = self.swap(CBUUID2)
    var b2Array = [b2 & 0xff, (b2 >> 8) & 0xff]
    if memcmp(&uuid1array, &b2Array, 2) == 0 {
        return 1
    }
    return 0
}

有两件事情似乎使事情复杂化.首先,不可能在Swift中声明一个固定大小的缓冲区,因此ObjC中的char b1 [16]在Swift中变为3行.其次,我不知道如何在Swift中使用UInt16进行memcmp().编译器抱怨说:

'UInt16' is not convertible to '@value inout $T5'

所以这就是笨重的步骤,我将UInt16分离成一个字节数组.

有什么建议?

最佳答案 char b1 [16]的相应Swift代码将是

var b1 = [UInt8](count: 16, repeatedValue: 0)

对于字节交换,您可以使用“内置”方法byteSwapped
或者bigEndian.
为memcpy()转换指针有点棘手.

将Objective-C代码直接转换为Swift(未经测试!):

var b1 = [UInt8](count: 16, repeatedValue: 0)
CBUUID1.data.getBytes(&b1, length: sizeofValue(b1))
var b2: UInt16 = CBUUID2.byteSwapped
// Perhaps better:
// var b2: UInt16 = CBUUID2.bigEndian
if memcmp(UnsafePointer(b1), UnsafePointer([b2]), 2) == 0 {
    // ...
}

但是,如果将b1定义为UInt16数组,则不需要
memcmp():

var b1 = [UInt16](count: 8, repeatedValue: 0)
CBUUID1.data.getBytes(&b1, length: sizeofValue(b1))
var b2: UInt16 = CBUUID2.bigEndian
if b1[0] == b2 {
    // ...
}
点赞