【问题标题】:XCTest: initialization of protocol variable is showing an error cannot be constructed because it has no accessible initializersXCTest:协议变量的初始化显示错误无法构造,因为它没有可访问的初始化程序
【发布时间】:2020-02-07 06:44:07
【问题描述】:

我需要访问协议,但出现以下错误:

'MyProtocol' cannot be constructed because it has no accessible initializers

这是我的实现:

public protocol MyProtocol{
    var someVar: Int {set get}
    var anotherVar: String {set get}
}


class ProtocolProjectTests: XCTestCase {
    var myProtocol: MyProtocol!

    override func setUp() {
        self.myProtocol = MyProtocol()
    }
}

在这条线上self.myProtocol = MyProtocol() 是我得到错误的地方。

我的问题是如何在 XCTest 类中初始化变量

非常感谢您的帮助。

【问题讨论】:

    标签: xctest ios13 xcode11 xctestcase swift5.2


    【解决方案1】:

    你需要用这个协议创建一些结构/类,例如:

    class MyProtocolMock: MyProtocol{
        var someVar: Int
        var anotherVar: String
    
        init() {
            someVar = 0
            anotherVar = ""
        }
    }
    

    然后就可以使用了:

    class ProtocolProjectTests: XCTestCase {
        var myProtocol: MyProtocol!
    
        override func setUp() {
            self.myProtocol = MyProtocolMock()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-21
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      相关资源
      最近更新 更多