kittonian
kittonian

Reputation: 1431

Swift Class Weak Var Init

Is there another way to initialize an already instantiated weak var optional in a class, other than passing it through the parameter? When dealing with multi-page forms, you end up having to instantiate on the previous page, just so you can pass it through correctly.

For example:

Current Method (passing everything through and initializing - works great but requires a lot of extra code, especially on previous pages of a multi-page form):

class Blah: ObservableObject {
    weak var user: User?
    weak var transfer: Transfer?

    init(user: User?, transfer: Transfer?) {
        self.user = user
        self.transfer = transfer
    }

    func test() {
        guard let user = user else { return }
        user.test = "foo"
    }
}

Preferred Method (if there's a different way to write the custom init so that you don't have to write all the extra code and deal with the previous pages of the form):

class Blah: ObservableObject {
    weak var user: User?
    weak var transfer: Transfer?

    init() {
       // better way to do it without passing through params
    }

    func test() {
        guard let user = user else { return }
        user.test = "foo"
    }
}

If you don't write the init, and you don't have the guard (unwrapping as optionals or explicit) the app will crash when these other observable classes are referenced because it sees the value as nil. Otherwise, with the guard statement, of course it just stops the function due to the return.

However, if you do initialize them, you need to pass everything through the previous page's navigationLink, which means there needs to be a reference to it on the previous page (hence instantiating on the previous page and then observing it on the actual page).

I don't see any way around manually initializing everything and writing all the extra code, but I thought I'd ask.

Upvotes: 0

Views: 592

Answers (1)

Nathan Day
Nathan Day

Reputation: 6037

I'm not sure a really understand, why can'y you just do

class Blah: ObservableObject {
    weak var user: User? = nil
    weak var transfer: Transfer? = nil

    func test() {
        guard let user = user else { return }
        user.test = "foo"
    }
}

also if you are initialising it from values in another object

class Blah: ObservableObject {
    weak var user: User?
    weak var transfer: Transfer?

    init(other: otherObject) {
        self.user = other.user
        self.transfer = other.transfer
    }

    func test() {
        guard let user = user else { return }
        user.test = "foo"
    }
}

or if Blah is to represent some state you want to pass around, why not have Blah as an instance in your other object

class Other {
    var blah: Blah
    // other properties methods
}

Upvotes: 0

Related Questions