我有协议:
protocol ConnectionServerProtocol {
func connectWithUsernameAndPassword(username: String, password: String)
}
我的课程符合这个协议:
public class ConnectionServer: NSObject {
var username: String?
var password: String?
let connectionServerProtocol: ConnectionServerProtocol
public init(connectionServerProtocol: ConnectionServerProtocol) {
self.connectionServerProtocol = connectionServerProtocol
}
}
我在该课程中有方法:
public func connectWithUsernameAndPassword(username: String, password: String) {
self.username = username
self.password = MD5(password)
self.connectionServerProtocol.dataTask()
}
我在ConnectionServer类中调用此方法,如下所示:
self.connectionServerProtocol.connectWithUsernameAndPassword(username:"someUserName", password: "SomePassword")
我有另一个类--ViewController,Q是 - 如何实例化(或不实例化)ConnectionServer从ViewController类调用connectWithUsernameAndPassword(username: "someUserName", password: "SomePassword")
?
我试图以不同的方式实例化ConnectionServer。
如果我这样做:
let cs = ConnectionServer()
我得到了:"无法为类型' ConnectionServer'调用初始化程序。没有参数" (显然)。
如果我这样做:
let cs = ConnectionServer(connectionServerProtocol:ConnectionServerProtocol)
我得到了:"参数类型' ConnectionServerProtocol.Protocol'不符合预期的类型' ConnectionServerProtocol'插入'如! ConnectionServerProtocol'" (显然也是)
如果我插入:
let cs = ConnectionServer(connectionServerProtocol: ConnectionServerProtocol.self as! ConnectionServerProtocol)
我得到了:"无法转换类型' SwiftCommons.ConnectionServerProtocol.Protocol' (0x10367dcb0)到' SwiftCommons.ConnectionServerProtocol'"
如果我这样做:
let cs = ConnectionServer.self
cs.connectWithUsernameAndPassword(username: SomeUserName", password:"SomePassword")
我得到了:"实例成员' connectWithUsernameAndPassword'不能在类型' ConnectionServer'"
上使用请帮忙。
UPD: 我重构了:
public class ConnectionServer: NSObject, ConnectionServerProtocol {
}
现在它符合协议。我应该解释一下,抱歉给您带来不便。 ConnectionServer和ConnectionServerProtocol的实现在我的Swift框架内部,我试图调用
cs.connectWithUsernameAndPassword(username: SomeUserName", password:"SomePassword")
来自该框架之外。