-2

I am getting the error Type 'CUnsignedChar?' has no subscript members which produces a lot of results in stackoverflow however I can't seem to utilise any of the other available answers for my example. Its clearly a casting issue but I don't not see how to overcome it

I am doing a obj-c to swift conversion and I have a variable being set up as follows

var bBuff1 = [CUnsignedChar](repeating: 0, count: Int(256*512))
var backGreyBuffer : CUnsignedChar = bBuff1[0]
//..
//..
var backGreyBufferOffset : Int = localTexOffset * 512
var grey_val = 0
self.backGreyBuffer[Int(backGreyBufferOffset)]! = grey_val; //Subscript error here

This is the obj-c code that uses in-outs.

unsigned char bBuff1[256*512];
unsigned char *backGreyBuffer = &bBuff1[0];

//..
grey_val = 0; 
backGreyBuffer[backGreyBufferOffset] = grey_val;

Any suggestions about the right direction would be great.

Allreadyhome
  • 1,252
  • 2
  • 25
  • 46
  • Why are you using char arrays in Swift, in the first place? – Alexander Feb 27 '17 at 22:11
  • What would be the alternative? – Allreadyhome Feb 27 '17 at 22:20
  • Just regular `String`. Even in Objective C, unless you're dealing with C APIs, you shouldn't be using `char *`, in favour of `NSString` instead – Alexander Feb 27 '17 at 22:21
  • Is a potential. I am just sticking to what the obj-c version implemented to connect to hardware. Though it is connecting to a C api – Allreadyhome Feb 27 '17 at 22:24
  • Even still, `String` and `NSString` can bridge to `char *` when necessary. It's completely nonsensical to work with raw char arrays in Swift. – Alexander Feb 27 '17 at 22:31
  • Roger. Thanks @Alexander. I will convert it properly – Allreadyhome Feb 27 '17 at 22:31
  • It's not a casting issue; you're using the address-of operator in the ObjC code and ending up with another pointer. In the Swift code you're not, so you don't get a pointer. But `&someBuffer[0]` is equivalent to `someBuffer` anyways, so that part's not really clear. – jscs Feb 27 '17 at 23:28

1 Answers1

0

I noticed that only a small change is needed in your code. You should make backGreyBuffer a pointer:

var bBuff1 = [CUnsignedChar](repeating: 0, count: Int(256*512))
var backGreyBuffer = UnsafeMutablePointer(mutating: bBuff1)

// ....

var backGreyBufferOffset = localTexOffset * 512
backGreyBuffer[backGreyBufferOffset] = grey_val
Mike Henderson
  • 2,028
  • 1
  • 13
  • 32