Return an array of type Self

I am having trouble finding a way to return an array of instances of a particular type of dynamic class at runtime in Swift.

I successfully compiled and tested this version, which returns a single instance of the class:

class Generic {

    class func all() -> Self {
        return self.init()
    }

    required init() {

    }

}

class A: Generic {

}

let a = A.all() // is of type A

The task here is to get compilation in order to allow functions to be allprototyped as follows: class func all() -> [Self](i.e. return an array of instances, working with subclasses, without casting ).

class Generic {

    class func all() -> [Self] {
        return [self.init()]
    }

    required init() {

    }

}

class A: Generic {

}

let a = A.all() // won't compile

Generic class func all() -> [Generic], A as!. begin A Self, "" . , , , ?

, , .

. , AnyObject. , , .

class Generic {

    class func all() -> [AnyObject] {
        return [self.init()]
    }

    required init() {

    }

}

class A: Generic {

}

let a = A.all() as! [A]

!

PS: / . "Swifty" , , . , , , , , .

+4
2

, , - , - , :

protocol Generic {

    func all() -> [Self]

    init()

}

extension Generic {

    func all() -> [Self] {
        return [self.dynamicType.init()]
    }

}

final class A : Generic {

}

A().all()

. -, , , . -, , , init, , all.

: init,

2: , , , , func all() -> [Self] static func all() -> [Self]

func all() -> [Self] {
    return [self.dynamicType.init()]
}

static func all() -> [Self] {
    return [self.init()]
}
0

, , Self. Self , [Self] Array<Self> .

, , , .

0

Source: https://habr.com/ru/post/1608347/


All Articles