Search code examples
swiftuint8t

Swift: Create Array of UInt8 with defined number of Values


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?


Solution

  • 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.