通过以下错误对类内的协议进行引用:预期的成员名称或类型名称后的构造方法调用

时间:2019-09-19 09:58:44

标签: swift xcode class swift-protocols

这是我目前的情况:

class FirstViewController: UITableViewController {
   ...
}

protocol SharedFunctions {
   func createEvent(event: Event, text: String)
}

extension FirstViewController: SharedFunctions {
   createEvent(event: Event, text: String) {
       ...
   }
}

class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
   var sharedFunctions = SharedFunctions? // < Xcode error...

   @IBAction func postChatMessageAction(_ sender: Any) {
       self.sharedFunctions.createEvent(event: event, text: "New Event")
   }
   ...
}
  

错误:类型名称后需要成员名称或构造函数调用

当我将代码更改为Xcode时,提示错误已消失,但在createEvent函数上收到错误消息

var sharedFunctions = SharedFunctions?.self //Xcode suggestion is adding .self

现在我在createEvent函数上遇到错误

@IBAction func postChatMessageAction(_ sender: Any) {
   self.sharedFunctions.createEvent(event: event, text: "New Event") // < Xcode error...
}
  

错误:键入“ SharedFunctions?”没有成员'createEvent'

我也尝试了以下错误:

weak var delegate = SharedFunctions? // < Xcode error...
  

错误:“弱”仅适用于类和类绑定的协议类型,不适用于“ SharedFunctions?.Type”

我想做的是,从我的SecondViewController类中触发我在FirstViewController类中拥有的函数createEvent()。

3 个答案:

答案 0 :(得分:1)

您的SharedFunctions声明语法错误。应该是

WITH ord AS ( SELECT '001' AS id,
       '111' AS order_id
FROM dual ), ord_his AS ( ( SELECT '001' AS id,
       '111' AS order_id,
       '456' AS transaction_id,
       'Reverted' AS events
FROM dual
) UNION ( SELECT '002' AS id,
       '111' AS order_id,
       '457' AS transaction_id,
       'Reverted' AS events
FROM dual
) ), ord_tran AS ( ( SELECT '001' AS id,
       '111' AS order_id,
       '456' AS transaction_id,
       100 AS qnty
FROM dual
) UNION ( SELECT '002' AS id,
       '111' AS order_id,
       '457' AS transaction_id,
       100 AS qnty
FROM dual
) ) SELECT ord.*,
       ord_his.transaction_id,
       events,
       qnty
FROM ord,
     ord_his,
     ord_tran
WHERE ord.order_id = ord_his.order_id AND ord_his.transaction_id = ord_tran.transaction_id;

答案 1 :(得分:0)

尝试

class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

   //Need change here
   var sharedFunctions : SharedFunctions? // < Xcode error...

     @IBAction func postChatMessageAction(_ sender: Any) {
      self.sharedFunctions.createEvent(event: event, text: "New Event")
     }
   ...
  }

答案 2 :(得分:0)

首先,func扩展名中缺少一个FirstViewController关键字。尝试像这样实现createEvent(event:text:)函数:

extension FirstViewController: SharedFunctions {
   func createEvent(event: Event, text: String) {
       ...
   }
}

除此之外,sharedFunctionsSecondViewController属性的声明是错误的。请尝试以下操作:

class SecondViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
   var sharedFunctions: SharedFunctions?

   @IBAction func postChatMessageAction(_ sender: Any) {
       self.sharedFunctions.createEvent(event: event, text: "New Event")
   }
   ...
}

希望这会有所帮助。