如何使用符合某个协议的属性声明swift类

如何使用符合某个协议的属性声明swift类,swift,Swift,swift是否有可能拥有一个从xib初始化的ViewController类,该类的属性也是UIViewController的子类,并且符合某些协议 protocol SomeProtocol { // Some methods } class ViewController: UIViewController { // contentView is initialized from xib @IBOutlet weak va

swift是否有可能拥有一个从xib初始化的
ViewController
类,该类的属性也是
UIViewController
的子类,并且符合某些协议

    protocol SomeProtocol {
        // Some methods
    }

    class ViewController: UIViewController {
        // contentView is initialized from xib
        @IBOutlet weak var contentView: UIView!

        // I'd like to declare anotherViewController both conforms to 'SomeProtocol' 
        // and a subclass of UIViewController
        var anotherViewController: UIViewController!
        ...
    }  
当我将
ViewController
声明为泛型类时,比如说
class ViewController
,我得到一个错误:

“通用类中的变量不能在Objective-C中显示”


所以,如果我不能使用泛型类,我该如何实现它呢?

如果我误解了您的问题,请原谅我,但我认为您要做的是声明一个从UIViewController继承并符合某些协议的新类型,如:

protocol SomeProtocol { }

class VCWithSomeProtocol: UIViewController, SomeProtocol {

}

class ViewController: UIViewController {
    var anotherViewController: VCWithSomeProtocol!
}

因此,我希望我没有误解这个问题,但听起来您可能需要一个多重继承对象级mixin,例如:

let myVC: ViewController, SomeProtocol
不幸的是,Swift不支持这一点。然而,有一个有点尴尬的工作可能会服务于您的目的

struct VCWithSomeProtocol {
    let protocol: SomeProtocol
    let viewController: UIViewController

    init<T: UIViewController>(vc: T) where T: SomeProtocol {
        self.protocol = vc
        self.viewController = vc
    }
}
struct vcsomeprotocol{
let协议:SomeProtocol
让viewController:UIViewController
init(vc:T),其中T:SomeProtocol{
self.protocol=vc
self.viewController=vc
}
}
然后,在需要执行UIViewController所具有的任何操作的任何地方,都可以访问结构的.viewController方面,以及需要协议方面的任何内容,都可以引用.protocol

例如:

class SomeClass {
   let mySpecialViewController: VCWithSomeProtocol

   init<T: UIViewController>(injectedViewController: T) where T: SomeProtocol {
       self.mySpecialViewController = VCWithSomeProtocol(vc: injectedViewController)
   }
}
class-SomeClass{
让mySpecialViewController:VCWithSomeProtocol
init(injectedViewController:T),其中T:SomeProtocol{
self.mySpecialViewController=VCWithSomeProtocol(vc:injectedViewController)
}
}
现在,无论何时需要mySpecialViewController执行任何与UIViewController相关的操作,只要引用mySpecialViewController.viewController,无论何时需要它执行某些协议功能,都可以引用mySpecialViewController.protocol

希望Swift 4将允许我们在将来声明一个带有附加协议的对象。但就目前而言,这是可行的


希望这有帮助

尝试反转两个,即class viewcontroller@MatthiasBauch的可能重复项,我不认为该链接解决了我的问题。我想要一个
UIViewController
属性,它符合某个协议,而不是一个符合某个协议的属性,可以用
UIViewController
@RajeevBhatia的子类来分配它不起作用:(谢谢!它确实解决了我的问题。但是,我必须使用SomeProtocol将许多视图控制器子类化为
VCWithSomeProtocol
,这不是我想要的。由于Swift不支持多重继承,我可能有自己的继承层次结构。