0

I have created a ViewController which is a subclass UIViewController. I have some properties which are defined nullable as shown below:

  // CloudKit 
    let container :CKContainer?
    let publicDB :CKDatabase?

Now, I initialize it using the init constructor method and Xcode complains that I also need to override the initWithCoder constructor which in my opinion feels kind of unnecessary.

 init() {

        container = CKContainer.defaultContainer()
        publicDB = container!.publicCloudDatabase

        super.init(nibName: nil, bundle: nil)
    }

    required init(coder aDecoder: NSCoder) {

        container = CKContainer.defaultContainer()
        publicDB = container!.publicCloudDatabase

        super.init(coder: aDecoder)
    }

I end up with lot of duplicate initialization code for container and publicDB as you can see above.

Is there a better way of doing the same as I have done?

john doe
  • 8,162
  • 20
  • 71
  • 141

1 Answers1

1

You could make a method called setup or something similar and shift these two lines

container = CKContainer.defaultContainer()
publicDB = container!.publicCloudDatabase

in that method. Then, in your different init methods, just call self.setup().


Edit

As a workaround to this problem, you could also make your container and publicDB variables optional (which they already are) and then set them up in viewDidLoad. That way, you will not have to write any init() methods at all.

aksh1t
  • 5,330
  • 1
  • 32
  • 53
  • Absolutely! I can do that but that is just moving the setup call to different initializers. Why do I even need a initWithCoder? It is marked with required but why it cannot just call the base/super implementation itself. – john doe Jun 14 '15 at 03:24
  • The thing with Swift is that if you override the `init` method of your superclass, you will also need to override the `initWithCoder:` initializer. Check out [this](http://stackoverflow.com/questions/24036393/fatal-error-use-of-unimplemented-initializer-initcoder-for-class) question. – aksh1t Jun 14 '15 at 04:05