Home:ALL Converter>Cannot assign value using a custom subscript method with a setter

Cannot assign value using a custom subscript method with a setter

Ask Time:2018-06-08T22:08:43         Author:askit

Json Formatter

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

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 ?

Author:askit,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50762496/cannot-assign-value-using-a-custom-subscript-method-with-a-setter