我有一个问题要解决。
这是需要工作的代码:
class A: NSObject, RowConvertible {
/// Initializes a record from `row`.
///
/// For performance reasons, the row argument may be reused during the
/// iteration of a fetch query. If you want to keep the row for later use,
/// make sure to store a copy: `self.row = row.copy()`.
public required init(row: Row) {
print(row)
}
}
extension A
{
public static func currentUser() -> Self?
{
// By key
let userType = type(of:self)
let user = try! dbQueue.inDatabase { db in
try self.fetchOne(db, "SELECT * FROM User")
}
return user
}
}
class B: A
{
}
let user = B.currentUser()
print(user)
RowConvertible
是一个包含fetchOne()
方法的协议(protocol)。
RowConvertible
是 GRDB.swift 开源库的一部分:
public protocol RowConvertible {
public static func fetchOne(_ db: Database, _ sql: String)
}
所以问题是,当我尝试对自身调用 fetchOne()
静态方法时,出现错误:
Type 'Self' has no member
fetchOne
but when I'm calling it onA
orB
classes it's OK.
所以我需要保持动态并自行调用该方法。
毕竟如果这项工作我还需要将返回值转换为 Self 类型。
提前致谢
格汉姆
最佳答案
protocol PrintProtocolTest {
static func printTest()
}
extension PrintProtocolTest {
static func printTest() {
print(self)
}
}
class A: PrintProtocolTest {
}
extension A {
static func test() {
self.printTest()
}
}
class B: A
{
}
B.test() /// <--- print 'B' here
可以得到结果
B
您的代码是正确的。使用 self
就可以了。
随着返回
protocol PrintProtocolTest {
static func printTest()
}
extension PrintProtocolTest {
static func printTest() {
print(self)
}
}
class A: PrintProtocolTest {
required init() {
}
}
extension A {
static func test() -> PrintProtocolTest {
self.printTest()
return self.init()
}
}
class B: A
{
}
B.test() // <--- return B instance here
关于ios - SWIFT:静态方法中的协议(protocol)功能在 "self"上不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42244841/