Cannot call 'append' using an argument list of type '(String)'
What is wrong here and how to fix 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] = [...]
The problem is that venues[venueIndex].rooms
it is not [String]
, but a [String]?
. Options have no method append
- the meaning within them might, but they are not.
You can use optional chaining to append in case it is not nil
:
venues[venueIndex].rooms?.append(room)
But you can instead rooms
initialize with rooms
an empty index when it is equal nil
, in which case you need to do a slightly more messy assignment instead of adding:
venues[venueIndex].rooms = (venues[venueIndex].rooms ?? []) + [room]
However, it's worth asking yourself, is it really necessary rooms
to be optional? Or could it just be an optional array with a starting value of empty? If so, it will likely simplify most of your code.
source to share