简体   繁体   English

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

[英]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.

相关问题 ASImageNode-无法分配给属性:“ image”是仅获取属性 - ASImageNode - Cannot assign to property: 'image' is a get-only property Swift协议扩展:无法分配给属性:''是一个只获取属性 - Swift Protocol extension: cannot assign to property: '' is a get-only property 无法分配给属性:'inputAccessoryView'是一个get-only属性 - Cannot assign to property: ‘inputAccessoryView’ is a get-only property 无法分配给属性:“ size”是仅获取属性Swift - Cannot assign to property: 'size' is a get-only property Swift 无法分配给属性:“值”是一个只能获取的属性 RxSwift - - Cannot assign to property: 'value' is a get-only property RxSwift - 无法分配给属性:“ itemArray”是仅获取属性 - Cannot assign to property: 'itemArray' is a get-only property 无法分配给属性'observationTime'是一个get-only属性 - Cannot assign to property 'observationTime' is a get-only property 无法分配给属性:“selectedDealClosingDate”是一个只能获取的属性 - SwiftUI - Cannot assign to property: 'selectedDealClosingDate' is a get-only property - SwiftUI 无法分配给属性:“订单”是仅获取属性 - Cannot assign to property: 'order' is a get-only property Swift:无法分配给属性:'reuseIdentifier' 是一个只读属性 - Swift: Cannot assign to property: 'reuseIdentifier' is a get-only property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM