Swift在回调中返回Self

时间:2015-02-04 08:27:57

标签: swift inheritance

是否可以在Swift中的超类方法中返回Self: 例如:

public class C {
    let name: String
    init(name:String) {
        self.name = name
    }

    public class func getByID(id:String, cb:(C->Void)) {
        // do something async
        cb( C(name: "Some name") )
    }
}

class CC: C {
}

CC.getByID("someId") { c in
    if let c = c as? CC {
        // I want this to happen
        println("c is of type CC")
    } else {
        println("c is not of type CC")
    }
}

如果我将cb类型替换为(Self-> Void),我会收到编译错误

'Self' is only available in a protocol or as the result of a class method; did you mean 'C'?

1 个答案:

答案 0 :(得分:1)

在类方法中,您可以使用self作为类本身。

并且,在这种情况下,您需要将初始值设定为required

public class C {
    let name: String
    required public init(name:String) {
//  ^^^^^^^^ HERE    
        self.name = name
    }

    public class func getByID(id:String, cb:(C->Void)) {
        // do something async
        cb( self(name: "Some name") )
        //  ^^^^ HERE
    }
}

增加:

  

但有没有办法避免在回调中向CC类转发?

这很困难,因为我们不能在参数类型中使用Self

我们能做到的最好是:

public class C {
    let name: String
    required public init(name:String) {
        self.name = name
    }

    public class func getByID<T: C>(id:String, cb:(T -> Void)) {
        if let instance = self(name: "Some name") as? T {
            cb(instance)
        }
        else {
            // `self` is not the type the callback expecting.
            // error handling if required.
        }
    }
}

然后你打电话:

CC.getByID("someId") { (c: CC) in
    println("c is of type CC")
}