Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Default property vs setting in initializer

Is there any drawback in swift to using a default property value instead of setting it in the initializer?

e.g.,

class Foo: UIViewController {
    let value = UIRefreshControl()
}

vs.

class Bar: UIViewController {
    var value : UIRefreshControl!

    // or using init()
    override func viewDidLoad() {
        self.value = UIRefreshControl()
    }
}

Default property values seem more terse and elegant, yet I don't see them used in code examples where they could be used.

like image 956
Adam Crabtree Avatar asked Oct 31 '22 10:10

Adam Crabtree


1 Answers

The only downside is that default property values are set every time an instance of the object is created, even if a property is subsequently overwritten in one or more initializers. This probably isn't an issue if you're just assigning default numeric values, but if there's a class that is expensive to construct you could end up doing twice the work.

like image 56
Nate Cook Avatar answered Nov 08 '22 08:11

Nate Cook