静态方法中的 Swift self

标签 swift

我想在静态方法中使用 self 作为类类型,但出现编译时错误。

这是我的测试代码:

protocol JSONMappable {
    static func map(JSON: AnyObject!) -> Self
}

class Model : JSONMappable, Mappable {   
    required init?(_ map: Map){

    }

    func mapping(map: Map) {

    }

    static func map(JSON: AnyObject!) -> Self {
        return Mapper<self>().map(JSON)
    }   
}

所以在静态方法映射中我想使用 self 作为类类型,我也尝试了 self.Type,但我得到了同样的错误。我不想使用类名,因为我需要此方法在 subclass 上调用时使用 subclass 类名。例如,如果我有:

class SubClass : Model {

}

并调用:

SubClass.map(JSON)

我需要在此方法中使用 SubClass 而不是 Model。 所以我想知道这是否可行?

最佳答案

protocol A {
    static func f()->Self
}
// class should conform to protocol A, so the returned type should be B
final class B: A {
    static func f() -> B {
        return B()
    }
}

let b = B()
let c = B.f()

我没有看到任何实际用法,因为 final 类不能被子类化并且要实现你的协议(protocol),该类应该声明为 final

对了,这个意思是一样的

protocol A {
    static func f()->Self
}

final class B: A {
    class func f() -> B {
        return B()
    }
}

没有静电

protocol A {
    func f()->Self
}

class B: A {
    func f()->Self {
        return self
    }
}
let a = B()
let b = a.f()

关于静态方法中的 Swift self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33371672/

相关文章:

ios - 如何使用 swift 作为 postman 请求测试来使用行 http 正文发出发布请求?

ios - 添加到 ScrollView 的 UIView 不适合全屏,导航栏位于顶部

ios - 无法调用非函数类型的值 'NSDictionary'

swift - Realm 的 setDefaultRealmSchemaVersion 未执行

swift - Flutter channel 方法字符串不能用作 URL

Swift 编译器宏(警告或停止)

ios - 导航栏按钮未显示在 PFQueryTableViewController(解析 + iOS)中

ios - Xcode 7 swift, '' 没有用 objective-c 选择器(函数)声明的方法”警告

swift - 如何在 Firebase 上查询带有时间戳的项目?

uitableview - Swift 中的自定义 UITableViewCell 注册类