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

前端 未结 1 1776
暖寄归人
暖寄归人 2021-02-09 15:26

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

相关标签:
1条回答
  • 2021-02-09 15:54

    The error occurs because you did not tell the compiler what to do if the value of currentBook is mutated. The compiler assumes it is immutable.

    Just add a setter so that the compiler knows what to do when you set the value:

    var currentBook: Book {
        get { return books[books.count - 1] }
        set { books[books.count - 1] = newValue }
    }
    

    Or, consider using books.last!:

    books.last!.position = CGPoint.zero
    
    0 讨论(0)
提交回复
热议问题