如何在Swift中执行memcmp()?

时间:2014-10-09 19:46:29

标签: objective-c swift

我试图将我的一些代码从Objective-C转换为Swift。我遇到问题的一种方法是对CBUUIDUInt16进行比较。这在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行。其次,我不知道如何使用UInt16在Swift中进行memcmp()。编译器抱怨说:

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

这就是笨重的步骤,我将UInt16手动分离成一个字节数组。

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

char b1[16]的相应Swift代码将是

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

并且对于字节交换,您可以使用“内置”方法byteSwappedbigEndian。 为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 {
    // ...
}