繁体   English   中英

Swift找不到协议保证的方法

[英]Swift can't find method guaranteed by protocol

我试图提出一种方法,以减少将Cleanse注入依赖关系到ViewController的样板代码。 但是,绝对Cleanse.Component我的Cleanse.Component样板放在类型擦除类中。 我究竟做错了什么?

(为了方便阅读,包括Code和XCode快照)

import Foundation
import Cleanse

protocol CleanseInjectable {
    func inject(args: Any...) -> Void
    func prepare() -> Void
}

extension CleanseInjectable {
    func inject(args: Any...) -> Void {

    }
}

class AnyCleansePropertyInjectionComponent<TargetType: AnyObject, CleanseInjectable>: Cleanse.Component {
    typealias Root = PropertyInjector<TargetType>

    func configure<B : Binder>(binder binder: B) {
        binder
            .bindPropertyInjectionOf(TargetType.self)
            .to(injector: (TargetType.self as! CleanseInjectable.Type).inject)
    }
}

我得到的错误与任何Swift协议错误一样奇怪,后者仅在事后才显而易见: Type 'CleanseInjectable' has no member 'inject'吗?

XCode快照

此修订版似乎已修复该错误! 看来Swift不能理解TargetType: AnyObject, CleanseInjectable在约束方面等效于protocol CleanseInjectable: class

import Cleanse

protocol CleanseInjectable: class {
    func inject(args: Any...) -> Void
    func prepare() -> Void
}

extension CleanseInjectable {
    func inject(args: Any...) -> Void {

    }
}

class AnyCleansePropertyInjectionComponent<TargetType: CleanseInjectable>: Cleanse.Component {
    typealias Root = PropertyInjector<TargetType>

    func configure<B : Binder>(binder binder: B) {
        binder
            .bindPropertyInjectionOf(TargetType.self)
            .to(injector: TargetType.inject)
    }
}

编辑:我完成的Cleanse样板去除器(在运行时未经试用,将尽快更新),以带来乐趣和启发!

import Cleanse

protocol CleanseInjectable: class {
    var cleanseComponent: AnyCleansePropertyInjectionComponent<Self>? { get }
    func inject(args: Any...) -> Void
    func prepare() -> Void
}

extension CleanseInjectable {
    func inject(args: Any...) -> Void {
        // Override me to do something useful, brah!
    }

    func prepare() -> Void {
        if (cleanseComponent != nil) {
            (try! cleanseComponent!.build()).injectProperties(into: self)
        }
    }
}

class AnyCleansePropertyInjectionComponent<TargetType: CleanseInjectable>: Cleanse.Component {
    typealias Root = PropertyInjector<TargetType>

    func configure<B : Binder>(binder binder: B) {
        binder
            .bindPropertyInjectionOf(TargetType.self)
            .to(injector: TargetType.inject)
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM