“Self”仅在协议中可用或作为类方法的结果

时间:2014-07-21 19:30:56

标签: swift

更新:由于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(), 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

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

1 个答案:

答案 0 :(得分:5)

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

解决方案是使用类名本身。这是结构Thing的一个例子:

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