2014-10-29 31 views
2

swift是否有可能讓ViewController類(從xib初始化)具有屬性也是UIViewController的子類並符合某些協議?如何聲明具有符合某些協議的屬性的swift類

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<T: UIViewController, SomeProtocol>,我得到一個錯誤:

"Variable in a generic class cannot be presented in Objective-C"

所以,我怎麼能實現它,如果我不能使用泛型類?

+0

嘗試顛倒兩個ie類ViewController 2014-10-29 09:58:51

+0

可能的重複[如何聲明具有類型和實現協議的變量?](http://stackoverflow.com/questions/25214484/how-do-i-declare-a-variable-that-has-a-type-and-implement -a-protocol) – 2014-10-29 10:16:11

+0

@MatthiasBauch我不認爲鏈接可以解決我的問題。我想要一個'UIViewController'屬性,它符合某種協議,而不是符合某種協議的屬性,並且可以用'UIViewController'的子類來分配。 – liuyaodong 2014-10-30 04:29:28

回答

1

請原諒我,如果我誤解了你的問題,但我想你想要做的就是聲明一個新的類型,從UIViewController的繼承和符合SomeProtocol,像這樣的內容:

protocol SomeProtocol { } 

class VCWithSomeProtocol: UIViewController, SomeProtocol { 

} 

class ViewController: UIViewController { 
    var anotherViewController: VCWithSomeProtocol! 
} 
+0

謝謝!它確實解決了我的問題,但是我必須製作很多視圖控制器子類VCWithSomeProtocol,這不是我想要的,因爲不支持多重繼承通過Swift,我可能擁有自己的繼承層次結構。 – liuyaodong 2014-10-30 04:36:33

0

所以我希望我沒有誤解的問題爲好,但它聽起來像是你可能需要一個多繼承對象級別混入如:

let myVC: ViewController, SomeProtocol 

不幸的是,斯威夫特並不支持這一點。然而,這可能有助於您的目的,但有些尷尬的解決方法。

struct VCWithSomeProtocol { 
    let protocol: SomeProtocol 
    let viewController: UIViewController 

    init<T: UIViewController>(vc: T) where 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) 
    } 
} 

現在,只要您需要mySpecialViewController做任何事情的UIViewController有關,你只是參考mySpecialViewController.viewController,每當你需要做一些協議功能,您引用mySpecialViewController.protocol。

希望Swift 4將允許我們在未來聲明一個附有協議的對象。但目前來看,這是有效的。

希望這會有所幫助!

相關問題