SWIFT:静态方法中的协议功能在" self"上不可见。

时间:2017-02-15 09:03:47

标签: 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()方法的协议。

RowConvertible是GRDB.swift开源库的一部分:

public protocol RowConvertible {

    public static func fetchOne(_ db: Database, _ sql: String)
}

问题是,当我试图在自己上调用fetchOne()静态方法时,我收到了错误:

  

键入' Self'没有会员fetchOne   但是当我在AB课程上调用它时,它就可以了。

所以我需要保持动态并在自己上调用该方法。

毕竟,如果这项工作我还需要将返回值转换为Self类型。

提前致谢

Gegham

1 个答案:

答案 0 :(得分:1)

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 

您可以获得结果

  

你的代码是对的。使用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
相关问题