Is it only possible to assign a value to a property inside `init`?

Hi ! In the following code, I can assign a value to total inside init, but not inside test. Why is that ?

struct PDFKitView: UIViewRepresentable {
    let url: URL
    let currentPage: Int
    let total: Int

    init(_ url: URL, _ currentPage: Int) {
        self.url = url
        self.currentPage = currentPage
        self.total = 1
    }
    
    func test () {
        self.total = 1
    }
// ...

The error is Cannot assign to property: 'total' is a let constant

let declares a constant. Constants are immutable. Once you set a value in an initializer, it cannot be changed anymore. var declares a variable that can be mutated. If you change let to var the error will change to:
error: cannot assign to property: 'self' is immutable
That is because functions in a struct assume that self is immutable. You can mark the function test as mutating and the compiler won't complain.

Nevertheless, seeing that you declared conformance to UIViewRepresentable, most likely you wanted to do something else.

1 Like

Thank you so much !

It's not a good idea to use a plain var variable (without a property wrapper like @State or @AppStorage) in a SwiftUI view like your PDFKitView. This is because SwiftUI views are destroyed and recreated whenever the system wants/needs to, so the value of your variable will just be thrown away.

Instead, you should use a coordinator. Here are two tutorials for that:

https://developer.apple.com/tutorials/swiftui/interfacing-with-uikit

1 Like