无法构造“DepartmentDataDelegate”,因为它没有可访问的初始值设定项
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法构造“DepartmentDataDelegate”,因为它没有可访问的初始值设定项相关的知识,希望对你有一定的参考价值。
我正在使用Protocol和Delegates将api数据保存到委托方法中,并在另一个类中提取它。但在第二堂课时,我宣布了这个属性。它显示一条错误消息。
无法构造“DepartmentDataDelegate”,因为它没有可访问的初始值设定项
A类:添加用于将api数据保存到委托方法的协议。
protocol DepartmentDataDelegate {
func showDepttData(departments: [String : Any])
}
var delegate: DepartmentDataDelegate?
将api数据存储到协议方法中
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: [Any]] {
//print("POST Method :(json)")
DispatchQueue.main.async {
for eachDepartment in json["departments"]!
{
let eachData = eachDepartment as! [String: Any]
self.delegate?.showDepttData(departments: eachData)
}
self.tableView.reloadData()
}
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
B类:此类正在获取部门数据并在此处打印。
class ShowEmpVC: UIViewController, DepartmentDataDelegate {
//Department Data Delegate
var depttDelegate = DepartmentDataDelegate()
var depttData = [String : Any]()
override func viewDidLoad() {
super.viewDidLoad()
depttDelegate = self
print("Departmens are : (depttData)")
}
}
答案
在您的协议中没有init()
功能。所以你不要打电话给DepartmentDataDelegate()
。试试这个:
A类:
protocol DepartmentDataDelegate {
func showDepttData(departments: [String : Any])
}
static var delegate: DepartmentDataDelegate?
B级:
class ShowEmpVC: UIViewController, DepartmentDataDelegate {
var depttData = [String : Any]()
override func viewDidLoad() {
super.viewDidLoad()
depttDelegate = self
print("Departmens are : (depttData)")
}
override func showDepttData(departments: [String : Any]){
// code
}
}
我不确定是否需要override
键。
另一答案
协议类
import UIKit
protocol sampleProtocol : class {
func getValues(valuess:String)
}
class sampleClass {
/// Shared Instance - So without creating a new Instance i can make use of its function
static let shared = sampleClass()
/// Delegate Object
var delegate : sampleProtocol?
/// Sample Func which will send data using protocol
func sendData(){
/// Called whnen data is to be Transmitted
delegate?.getValues(valuess: "output")
}
}
用法 - 目标类 - 您的案例ShowEmpVC
import UIKit
class sampleVC: UIViewController
{
override func viewDidLoad() {
super.viewDidLoad()
/// Make use of Shared Instance Created so, You need not to Re-allocate a New instance just to make use of Delegate
sampleClass.shared.delegate = self
}
}
/// Assign class to Protocol
extension sampleVC : sampleProtocol
{
/// Protocol stub
func getValues(valuess: String) {
/// Get Value
print(valuess)
}
}
以上是关于无法构造“DepartmentDataDelegate”,因为它没有可访问的初始值设定项的主要内容,如果未能解决你的问题,请参考以下文章
无法解析片段中的 ViewModelProvider 构造?
无法构造 java.util.LinkedHashMap 的实例:没有字符串参数构造函数/工厂