Reputation:
What is wrong here and how to solve this problem?
struct Venue {
let building: String
var rooms: [String]?
}
func addRoom(building: String, room: String) {
if let venueIndex = find(venues.map {$0.building}, building) {
venues[venueIndex].rooms.append(room) //Cannot invoke 'append' with an argument list of type'(String)'
}
}
var venues: [Venue] = [...]
Upvotes: 3
Views: 4175
Reputation: 40965
The problem is that venues[venueIndex].rooms
is not a [String]
but a [String]?
. Optionals don’t have an append
method – the value wrapped inside them might, but they don’t.
You could use optional chaining to do the append in the case where it isn’t nil
:
venues[venueIndex].rooms?.append(room)
But you may instead want to initialize rooms
to an empty index instead when it is nil
, in which case you need to do a slightly messier assignment rather than an append:
venues[venueIndex].rooms = (venues[venueIndex].rooms ?? []) + [room]
However, it is worth asking yourself, does rooms
really need to be optional? Or could it just be a non-optional array with a starting value of empty? If so, this will likely simplify much of your code.
Upvotes: 5