【问题标题】:Swift: using instance of a generic type associatedtype segfaults compilerSwift:使用泛型关联类型段错误编译器的实例
【发布时间】:2016-07-11 20:39:19
【问题描述】:

当我尝试编译以下代码时遇到分段错误。我正在尝试在 CellUpdater 结构上进行类型约束扩展,该结构访问一个属性,该属性的类型是在泛型类型的关联类型上定义的。不确定我是否做错了什么,或者它是否是 Swift 编译器的限制,有什么想法吗?

protocol CellUpdaterType {
    func generateDetailsDrillDownController(index: Int) -> UIViewController?
}

extension CellUpdaterType {
    func generateDetailsDrillDownController(index: Int) -> UIViewController? { return nil }
}


struct CellUpdater<Cell where Cell: UpdatableView> : CellUpdaterType {
    let viewModel: Cell.ViewModel
}

extension CellUpdater where Cell: HeadlineCell {
    func generateDetailsDrillDownController(index: Int) -> UIViewController? {
        let storyboard = UIStoryboard(name: "SomeStoryboard", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("SomeViewController") as? SomeViewController
        vc?.headline = viewModel.headline // This line crashes the compiler
        return vc
    }
}

class HeadlineCell: UITableViewCell {
    var headline: Headline?
    // ...
}


extension HeadlineCell : UpdatableView {
    typealias ViewModel = HeadlineCellViewModel
    func update(viewModel viewModel: ViewModel) {
    // ...
    }
}


struct HeadlineCellViewModel {
    let headline: Headline

    init(headline: Headline) {
        self.headline = headline
    }
}

protocol UpdatableView: class {
    associatedtype ViewModel
    func update(viewModel viewModel: ViewModel)
}

【问题讨论】:

  • 虽然这在 Xcode 7.3.1 中确实存在段错误,但它在 Xcode 8 beta 2 中编译:)

标签: ios swift generics associated-types


【解决方案1】:

我认为它可能与编译器无法在编译时修复您的视图模型类型有关,这在 Swift 中是必需的。不过,它可能已在 Swift 3.0 中修复。我已经设法稍微更改了您的代码,因此它现在可以编译了。主要区别在于限制视图模型而不是 CellUpdater 扩展中的单元格。

struct CellUpdater<Cell where Cell: UpdatableView> : CellUpdaterType {
    typealias ViewModel = Cell.ViewModel

    let viewModel: ViewModel
}

extension CellUpdater where Cell.ViewModel : HeadlineCellViewModelType {
    func generateDetailsDrillDownController(index: Int) -> UIViewController? {
        let storyboard = UIStoryboard(name: "SomeStoryboard", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("SomeViewController") as? SomeViewController
        vc?.headline = viewModel.headline
        return vc
    }
}

protocol HeadlineCellViewModelType {
    var headline: Headline { get }
}

struct HeadlineCellViewModel : HeadlineCellViewModelType {
    let headline: Headline

    init(headline: Headline) {
        self.headline = headline
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2021-08-06
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多