swift - swift UIViewController 子类中的非可选 var

标签 swift

import Foundation
import RentalsService

class RentalsViewController: UIViewController {

    var rentalService: Rentals

    init(rentalService: Rentals) {
        self.rentalService = rentalService
        super.init(nibName: "RentalsViewController", bundle: NSBundle.mainBundle())

    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder) // problem here
    }

}

我希望 rentalService 变量是非可选的。也就是说,如果没有该服务,您就无法拥有 rentalsVC。但是,我被迫声明 init(NSCoder) - 但此时我无法访问租赁服务实现。

Rentals 是一种协议(protocol),我正在使用依赖项注入(inject) - 因此不会在类内部创建依赖项。

有人有什么聪明的想法来克服这个问题吗?或者什么是首选模式/最佳实践?

最佳答案

如果你不想支持 NSCoding,你可以这样做:

required init(coder: NSCoder) {
  fatalError("NSCoding not supported")
}

此处引用:https://stackoverflow.com/a/25128815/2611971

关于swift - swift UIViewController 子类中的非可选 var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26366150/

相关文章:

ios - ios 一根手指捏合手势

ios - 如何调用 MasterVC 上的函数,通过取消推送的 VC 来执行?

ios - 使用新的 Swift 3 和 Alamofire 解析 JSON

ios - Apple 是如何在 Apple Music 中制作专辑封面背后的模糊效果的?

ios - 选择要加载到 TableView Swift 中的数据

ios swift siesta ResourceObserver resourceRequestProgress 从未调用过

ios - 同时使用 CoreLocation 和 CoreBluetooth 扫描信标

ios - swift : fatal error: unexpectedly found nil and EXC_BAD_INSTRUCTION

xcode - Storyboard中的 NSStatusBar 项目 (OSX)

ios - 在具有自定义 TableViewCell 的单个 ViewController 中使用多个 UITableview