Setting up properties


(Erica Sadun) #1

For a friend:

This won't work.

class DerpController {
    private(set) var derp: Bool = {
        return _findDerp() != nil
    }()
    
    private func _findDerp() -> AnyObject? {
        return nil
    }
}

but this works:

private func _findDerp() -> AnyObject? {
    return nil
}

class DerpController {
    private(set) var derp: Bool = {
        return _findDerp() != nil
    }()
    
}

Is it because the var member cannot depend on another member during setup? Thanks in advance for insight.


(Joe Groff) #2

Yeah, instance methods can't be called until `self` is fully initialized, since they may themselves touch the uninitialized instance. In addition to making the function global, you could also make it a static method to preserve namespacing.

···

On Dec 21, 2015, at 5:14 PM, Erica Sadun via swift-users <swift-users@swift.org> wrote:

For a friend:

This won't work.

class DerpController {
    private(set) var derp: Bool = {
        return _findDerp() != nil
    }()
    
    private func _findDerp() -> AnyObject? {
        return nil
    }
}

but this works:

private func _findDerp() -> AnyObject? {
    return nil
}

class DerpController {
    private(set) var derp: Bool = {
        return _findDerp() != nil
    }()
    
}

Is it because the var member cannot depend on another member during setup? Thanks in advance for insight.


(Erica Sadun) #3

Thanks. Passed that along back.

-- E

···

On Dec 21, 2015, at 7:47 PM, Joe Groff <jgroff@apple.com> wrote:

Yeah, instance methods can't be called until `self` is fully initialized, since they may themselves touch the uninitialized instance. In addition to making the function global, you could also make it a static method to preserve namespacing.


(David Turnbull) #4

You could be lazy about it...

    lazy private(set) var derp: Bool = {

        [unowned self] in

        return self._findDerp() != nil

    }()

···

On Mon, Dec 21, 2015 at 6:54 PM, Erica Sadun via swift-users < swift-users@swift.org> wrote:

Thanks. Passed that along back.

-- E

On Dec 21, 2015, at 7:47 PM, Joe Groff <jgroff@apple.com> wrote:

Yeah, instance methods can't be called until `self` is fully initialized,
since they may themselves touch the uninitialized instance. In addition to
making the function global, you could also make it a static method to
preserve namespacing.

_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users


(Erica Sadun) #5

Thanks again! -- E,passed on

···

On Dec 21, 2015, at 8:15 PM, David Turnbull via swift-users <swift-users@swift.org> wrote:

You could be lazy about it...
    lazy private(set) var derp: Bool = {
        [unowned self] in
        return self._findDerp() != nil
    }()