swift – ‘Self’仅在协议中可用或作为类方法的结果

前端之家收集整理的这篇文章主要介绍了swift – ‘Self’仅在协议中可用或作为类方法的结果前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
更新:由于 SE-0068 – Expanding Swift Self to class members and value types,Swift 3允许使用其他类型的Self.

您可以从类函数返回“Self”:

extension NSObject {
    class func makeOne() -> Self {
        return self()
    }
}

所以你可以这样做:

let set : NSCountedSet = NSCountedSet.makeOne()

但是,以下两个不编译:

extension NSObject {
    class func makeTwo() -> (Self,Self) {
        return (self(),self())
    }

    class func makeMany() -> [Self] {
        return [self(),self(),self()]
    }
}

错误是:

<REPL>:11:34: error: 'Self' is only available in a protocol or as the result of a class method; did you mean 'NSObject'?
        class func makeTwo() -> (Self,Self) {
                                 ^~~~
                                 NSObject
<REPL>:11:40: error: 'Self' is only available in a protocol or as the result of a class method; did you mean 'NSObject'?
        class func makeTwo() -> (Self,Self) {
                                       ^~~~
                                       NSObject
<REPL>:15:35: error: 'Self' is only available in a protocol or as the result of a class method; did you mean 'NSObject'?
        class func makeMany() -> [Self] {
                                  ^~~~
                                  NSObject

有没有人知道有什么方法可以声明类函数返回类本身的多个实例?

我怀疑,问题在于自我是模棱两可的;它意味着“这个类或子类,无论我们被称为什么时发生的事情”.换句话说,Self是多态的.但是,例如,您无法创建由两个不同类组成的数组.虽然该类可能允许某个初始化程序,但我们无法事先知道它的子类将会.

解决方案是使用类名本身.这是一个struct Thing的例子:

extension Thing {
    static func makeTwo() -> (Thing,Thing) {
        return (Thing(),Thing())
    }
}

猜你在找的Swift相关文章