ios - SWIFT:静态方法中的协议(protocol)功能在 "self"上不可见

标签 ios swift sqlite casting

我有一个问题要解决。

这是需要工作的代码:

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 on A or B 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/

相关文章:

ios - 加密通过 Core Data 访问的 Sqlite 数据库

ios - 更改 Xcode 中的开发语言

ios - 方法 Swizzling 未正确触发?

IOS App Submission with Encryption/Fairplay,怎么做或者自动

javascript - 如何使用 iv 和 key 与 cryptoswift 进行 AES 解密?

ios - 在 swift 4 中处理 JSON

ios - 如果用户拒绝相机访问,则无法显示警报

swift - Swift 中以 NSException 类型的未捕获异常终止

c++ - SQLITE3 增加 Max Columns

sql - 测试 SQLite 触发器内的 COUNT()>X