从任何VC获取协议定义的变量值

时间:2016-09-30 14:44:34

标签: ios swift2 swift-protocols swift-extensions

协议(myProtocol): -

 protocol myProtocol {
        var type:String { get set }
        var sub:String { get }
        var msg:String? { get set }
    }

类(myVC): -

class myVC: UIViewController, myProtocol {
    //Protocol Declarations
    var sub  = myTypes.type.rawValue
    var type = myTypes.type.getType()
    var msg :String?

.... }

扩展: -

extension UIViewController
{
 func getData() {
        if self is myProtocol {
         let msg = self.msg

        } }
}

在'self.msg'上收到错误,说Value of type UIViewController has no member 'sub'

我该怎么做? 任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:1)

您需要做的就是在扩展类中编写另一行代码。我刚刚测试了它,它对我有用。这是我写的代码 -



extension UIViewController
{
    func getData() {
        if self is myProtocol {
            let x = self as! myProtocol
            let msg = x.msg
            print(x.msg)
        }
    }
}




答案 1 :(得分:0)

根据您的示例,您需要更改扩展名定义

extension UIViewController

as

extension myVC