Reputation: 5722
I can't seem to get collections to be mutable when they are assigned to optional variables. In the sample code below, the NonOptional works as expected. A var will keep the mutable state on the collection. No local vars, I can use the variable field directly. However I am not sure how to have vars with immutable collections, should I assume "let" instead of "var" would do the trick?
Nevertheless, looking at the Optional class, one requires a local var to give the collection a mutable state (even if XCode suggests append() when I don't use the local var). Is this really the way I am supposed to write code to update collection by adding local variables? Is there a more concise way without using a local var? I am curious to know if the assignment of a collection is a simple alias or does it do a copy, either shallow or deep underneath?
class NonOptional {
var exclamation: String[] // using var should set that collection as mutable...
init() {
self.exclamation = []
}
func write() {
self.exclamation.append("exclamation")
}
func delete() {
if self.exclamation.count > 0 {
self.exclamation.removeAtIndex(0)
}
}
}
class Optional {
var question: String[]? // using var should set that collection as mutable...
init() {
self.question = []
}
func write() {
var local = self.question! // copy or pass by ref?
local.append("question") // why can't I just do self.foo!.append("foo") ?
}
func delete() {
if self.question!.count > 0 {
var local = self.question!
local.removeAtIndex(0)
}
}
}
Upvotes: 1
Views: 418
Reputation: 135578
This question was asked when Swift 1 was still in beta, and much has changed since (though I'm not entirely sure if this particular feature didn't exist in Swift 1).
For posterity, mutating an optional array is no problem in Swift 3. Here's how you would do it:
var strings: [String]? = ["a", "b"]
strings?[0] = "A"
// strings is now Optional(["A", "b"])
strings?.append("c")
// strings is now Optional(["A", "b", "c"])
strings?.remove(at: 1)
// strings is now Optional(["A", "c"])
Upvotes: 2
Reputation: 5022
var question: String[]? // using var should set that collection as mutable...
This is wrong. The var
there says that the optional reference is 'mutable', that is it can be nil
or set to an actual array. Swift then defaults to making the array non mutable.
Many of these smaller details concerning arrays and mutability are a bit in flux at the moment, I expect there to be fixes, changes and a clear definition of what is supposed to happen in the coming weeks.
Upvotes: 0