无法分配给属性:'xxxx'是get-only属性

sid*_*ick 2 swift computed-properties

我正在使用计算属性来获取我的books数组中的最后一本书.但是,我似乎无法使用此属性直接设置图书的position属性,因为我的下面的尝试显示:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

以下工作,但我希望它更具可读性单行.

books[books.count - 1].position = CGPoint.zero
Run Code Online (Sandbox Code Playgroud)

我可以使用函数返回当前的书,但使用属性会更干净.还有另外一种方法吗?

Swe*_*per 8

发生该错误是因为如果变量值没有告诉编译器该怎么做currentBook.编译器假定它是不可变的.

只需添加一个setter,以便编译器在设置值时知道该怎么做:

var currentBook: Book {
    get { return books[books.count - 1] }
    set { books[books.count - 1] = newValue }
}
Run Code Online (Sandbox Code Playgroud)

或者,考虑使用books.last!:

books.last!.position = CGPoint.zero
Run Code Online (Sandbox Code Playgroud)

  • 这有点奇怪,因为计算属性必须声明为`var` ... (7认同)