2

I have a project where I write the production code in Swift and my unit tests in Objective-C (because I'm using OCMock I write my tests in Objective-C).

What I'm trying to do is to write a Buffer object where the writeBytes method takes a Byte array and a length, like this:

func writeBytes(data: [Byte], length: Int)

In my unit test target I want to test this method, but the problem is that it won't convert this method to Objective-C. By looking in my -Swift.h file I see the following:

@interface Buffer : Object
@property (nonatomic) NSInteger capacity;
@property (nonatomic) NSInteger size;
- (instancetype)initWithCapacity:(NSInteger)capacity OBJC_DESIGNATED_INITIALIZER;
- (void)reset;
- (NSInteger)size;
- (BOOL)isFilled;
- (BOOL)isEmpty;
@end

As you can see the writeBytes method is missing. I've tried different data types to see if it appears: UInt8, UnsafePointer<UInt8>, but none of them work.

For the sake of debugging I tried using a String array and that gets converted to Objective-C without any problems.

What data type should I use for my Byte array to make the writeBytes method available in Objective-C?

2
  • Are you sure you're recompiling each time? Commented Jul 17, 2014 at 8:34
  • Yes, since it is working with String arrays I know the file gets updated. Commented Jul 17, 2014 at 8:51

2 Answers 2

3

The Swift type [Byte] is not representable in Objective-C, but you can work with a pointer to the bytes:

func writeBytes(data: ConstUnsafePointer<Byte>, length: Int) { ... }

var data : [Byte] = [1, 2, 3]
writeBytes(data, length: data.count)

This mapped to Objective-C as

- (void)writeBytes:(Byte const *)data length:(NSInteger)length;

so that you can call it like

Byte data[] = {1, 2, 3};
[buffer writeBytes:data length:3];
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, nice! This works, thank you! I only tested it with [UnsafePointer<Byte>] and not as you suggested.
@Downvoter: It would be helpful to know what is wrong about this answer, so that I can fix it if necessary ...
1

Use NSData. You can create one from an array of [UInt8] in Swift as:

import Foundation
var u8s = [UInt8]()
// ...
var data = NSData(bytes:&u8s, length:u8s.count)

FYI this is the opposite of Swift - converting from ConstUnsafePointer<()> where the questioner was looking for the way to convert NSData to [UInt8].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.