3

How is it possible to create an Array of UInt8 in Swift? I've tried this with the following code:

var array: [UInt8] = [UInt8]()

Now I want to loop through a second UInt variable a :

for var i: Int = 0; i < a.count; i++ {
    array[i] = UInt8(a[i]^b[i])
}

But then I get the following error :

fatal error: Array index out of range

When I put the same bits as a -> [0x01,0x01,0x01,0x01,0x01] in the variable array then the loop works fine!

Does anybody know why?

Fantattitude
  • 1,842
  • 2
  • 18
  • 34
user3143691
  • 1,533
  • 3
  • 11
  • 19

4 Answers4

10

From Collection Types in the Swift documentation:

You can’t use subscript syntax to append a new item to the end of an array.

There are different possible solutions:

Create the array with the required size, as @Fantattitude said:

var array = [UInt8](count: a.count, repeatedValue: 0)
for var i = 0; i < a.count; i++ {
    array[i] = UInt8(a[i]^b[i])
}

Or start with an empty array and append the elements, as @Christian just answered:

var array = [UInt8]()
for var i = 0; i < a.count; i++ {
    array.append(UInt8(a[i]^b[i]))
}

The "swifty" way in your case however would be a functional approach with zip() and map():

// Swift 1.2 (Xcode 6.4):
let array = map(zip(a, b), { $0 ^ $1 })
// Swift 2 (Xcode 7):
let array = zip(a, b).map { $0 ^ $1 }

zip(a, b) returns a sequence of all pairs of array elements (and stops if the shorter array of both is exhausted). map() then computes the XOR of each pair and returns the results as an array.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
6

You could use init(count: Int, repeatedValue: Element) of Array like this :

var array = [UInt8](count: 5, repeatedValue: 0x01)

To learn more about Array initializers take a look here : http://swiftdoc.org/swift-2/type/Array/

Fantattitude
  • 1,842
  • 2
  • 18
  • 34
2

You can initialise the array using the count of your second array so as not to get the index out of range error.

var array = [UInt8](count: a.count, repeatedValue: 0x00)

or you can use the append method of array in your loop.

for var i:Int = 0; i < a.count; i++
{
   array.append( UInt8(a[i]^b[i]) )
}
Christian Abella
  • 5,747
  • 2
  • 30
  • 42
0

On Swift 3 onwards is:

var array = [UInt8](repeating: 0, count: 30)
joan
  • 2,407
  • 4
  • 29
  • 35