Cannot assign to property: 'xxxx' is a get-only property

Viewed 44921

I'm using a computed property to get the last book in my books array. However, it seems I can't use this property to directly set a book's position property, as my attempt below shows:

struct Book {
    var position: CGPoint?
}

class ViewController: UIViewController {

    var books = [Book]()

    var currentBook: Book {
        return books[books.count - 1]
    }

    func setup() {
        // Compiler Error: Cannot assign to property: 'currentBook' is a get-only property
        currentBook.position = CGPoint.zero
    }
}

The following works but I'd like it to be more readable and a single line.

books[books.count - 1].position = CGPoint.zero

I could use a function to return the current book but using a property would be cleaner. Is there another way?

1 Answers
Related