简体   繁体   中英

Swift Array extension with struct and generic object

So I have this code:

struct Asset<T>: AssetProtocol{
    typealias AssetType = T

    var parent: T!
    var children: [T]!
    init(parent: T, children: [T] = [T](),){
        self.parent = parent
        self.children = children
    }
}

protocol AssetProtocol{
    associatedtype AssetProtocolType
    var parent: AssetProtocolType! { get }
    var children: [AssetProtocolType]! { get }
}

extension Array where Element: AssetProtocol{
    fun getExtractParents() -> [<I’m not sure what type should be here the “T” doesn’t work>] {
        // iterate here to get all the parents then return it. 
    }
}

Is there a way that I can create an Array extension and a method inside it that returns all the "parent" in that array? note that the type of the "parent" is generic as shown in the struct Asset.

So I think I found the answer. I'm not sure if this is correct or efficient but it does the work for me.

extension Array where Element: AssetProtocol{
    func extractParents() -> [Element.AssetProtocolType] {
        var parents: [Element.AssetProtocolType] = []
        for element in self {
            parents.append(element.parent)
        }

        return parents
    }
}

I'm still open for suggestion if anyone would give...

Your solution works, but there is a slightly more efficient and... Swifty way:

extension Array where Element: AssetProtocol {
    var parents: [Element.AssetProtocolType] {
        return self.map( { $0.parent } )
    }
}

Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM