Q:

Cannot assign value using a custom subscript method with a setter

This is from apple's official documentation(slightly modified) -
class Person {
    var residence: Residence?
}

class Residence {
    var rooms = [Room]()
    var numberOfRooms: Int {
        return rooms.count
    }
    subscript(i: Int) -> Room {
        get {
            return rooms[i]
        }
        set {
            rooms[i] = newValue
        }
    }
}

class Room {
    let name: String
    init(name: String) { self.name = name }
}

let john = Person()
let johnsHouse = Residence()

johnsHouse.rooms.append(Room(name: "Living Room")) 
johnsHouse.rooms.append(Room(name: "Kitchen"))
john.residence = johnsHouse 

let firstRoomName = john.residence?[0].name
print(firstRoomName)

prints - Optional("Living Room")
So, above program uses getter (even if I omit setter, prints the same). This time I want to use setter instead of getter. How to go about it ? 

A:

You can assign a value to a specific element of Residence.rooms just like you would do for a normal Array. The subscript method of Residence simply makes it possible to leave out .rooms when accessing a specific element of Residence.rooms, so you can simply do Residence[n] to access Residence.rooms[n].
So if you want to assign a value to a Room by calling the setter of Residence.subscript, you simply need to do
john.residence?[0] = Room(name: "Bedroom")

The setter of subscript only gets called when you assign a value to the value returned by the subscript like in the code above.
Be aware that the subscript method of Residence doesn't guard against out of range access, so you cannot add new elements to the rooms array using the subscript setter method. So for instance following your example code if you tried to add a 3rd room instead of modifying one of the two existing rooms by doing john.residence?[2] = Room(name: "Bedroom"), you'd receive a runtime "Index out of range." error.

