Home > database >  How to convert bytes propertu from Objective C to Swift?
How to convert bytes propertu from Objective C to Swift?

Time:11-14

I have a simple objective c function:

- (NSData *)xorData1:(NSData *)data1 data2:(NSData *)data2 resultLength:(NSInteger)length {
    const char *data1Bytes = [data1 bytes]; // ??
    const char *data2Bytes = [data2 bytes]; // ??

    NSMutableData *xorData = [[NSMutableData alloc] init];
    for (int i = 0; i < length; i  ) {
        const char xorByte = data1Bytes[i % data1.length] ^data2Bytes[i % data2.length];
        [xorData appendBytes:&xorByte length:1];
    }
    return xorData;
}

and I need to make it working in Swift, how can I do it?

import CommonCrypto

func xor(firstData: Data, secondData: Data) -> Data {
    let length = kCCKeySizeAES128
    let firstDataBytes = firstData // ??
    let secondDataBytes = secondData // ??
    let xorData = NSMutableData()
    for i in 0..<length {
        var xorByte = firstDataBytes[i % firstData.count] ^ secondDataBytes[i % secondData.count];
        xorData.append(&xorByte, length: 1)
    }
    return xorData as Data
}

CodePudding user response:

Your Swift function compiles, and should produce the same results as the Objective-C function. A bytes property is not needed since Data is a Collection and the underlying bytes can be accessed by subscript:

let d = Data([11, 22, 33, 44, 54])
print(d[2]) // 33

There is also no need to use the Cocoa class NSMutableData, it is simpler to work with the Swift Data type throughout:

func xor(firstData: Data, secondData: Data) -> Data {
    let length = kCCKeySizeAES128
    var xorData = Data()
    for i in 0..<length {
        let xorByte = firstData[i % firstData.count] ^ secondData[i % secondData.count];
        xorData.append(xorByte)
    }
    return xorData
}

Or, using the map function:

func xor(firstData: Data, secondData: Data) -> Data {
    let length = kCCKeySizeAES128
    return Data((0 ..< length).map {
        firstData[$0 % firstData.count] ^ secondData[$0 % secondData.count]
    })
}
  • Related