Update
In the version of Swift provided with Xcode 6 Beta 5, the bug is fixed and the code runs normally (after adaptation, of course), here's the new code:
class Test {
var items:[String]?
func process() {
if (self.items == nil) {
self.items = [String]()
}
for i in 1...5 {
var item = String(i)
self.items!.append(item)
}
}
}
Old Answer
I have found that the result of unwrapping is a constant, and a constant can't be mutated. Thus the error "Could not find an overload for '+=' that accepts the supplied arguments." since the operator '+=' is defined as:
@assignment func +=<A : ArrayType>(inout lhs: A, rhs: A._Buffer.Element)
So as solution you can either use @lazy attribute (as suggested by GoZoner and seen in drewag's answer) or David's method of creating a temporary variable.
Method 1 (@lazy):
Taken from drewag's answer
class Test {
@lazy var items = String[]()
func process() {
for i in 1...5 {
var item = String(i)
self.items.append(item)
}
}
}
Method 2 (temporary variable):
Taken from David's answer
class Test {
var items : String[]?
func process() {
var items = self.items ? self.items! : String[]()
for i in 1...5 {
var item = String(i)
items += item;
}
self.items = items
}
}