[英]Cannot assign to property: 'xxxx' is a get-only property
I'm using a computed property to get the last book in my books
array. 我正在使用计算属性来获取我的books
数组中的最后一本书。 However, it seems I can't use this property to directly set a book's position
property, as my attempt below shows: 但是,我似乎无法使用此属性直接设置书籍的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
}
}
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? 还有另外一种方法吗?
The error occurs because you did not tell the compiler what to do if the value of currentBook
is mutated. 发生错误是因为如果currentBook
的值发生变异,您没有告诉编译器该怎么做。 The compiler assumes it is immutable. 编译器假定它是不可变的。
Just add a setter so that the compiler knows what to do when you set the value: 只需添加一个setter,以便编译器在设置值时知道该怎么做:
var currentBook: Book {
get { return books[books.count - 1] }
set { books[books.count - 1] = newValue }
}
Or, consider using books.last!
或者,考虑使用books.last!
: :
books.last!.position = CGPoint.zero
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.