简体   繁体   中英

Swift 3, Extend Array where items of Array are of a certain type

I've written a struct that holds basic Asset data:

struct Asset: AssetProtocol {

    init (id: Int = 0, url: String) {
        self.id = id
        self.url = URL(string: url)
    }

    var id: Int 
    var url: URL?

}

It subscribes to AssetProtocol

protocol AssetProtocol {
    var id: Int { get }
    var url: URL? { get }
}

I'm hoping to extend the Array (Sequence) where the elements in that Array are items that subscribe to the AssetProtocol. Also, for these functions to be able to mutate the Array in place.

extension Sequence where Iterator.Element: AssetProtocol {

    mutating func appendUpdateExclusive(element newAsset: Asset) {    
        ...

How can I iterate through and mutate this sequence? I've tried half a dozen ways and can't seem to get it right!

Rather than using a method which takes an Asset as an argument, consider reusing Element instead. Since you've already defined the constraint on Element in your extension definition, all methods and properties on AssetProtocol will be available on the instance of Element :

protocol AssetProtocol {
    var id: Int { get }
    var url: URL? { get }

    static func someStaticMethod()
    func someInstanceMethod()
}

extension Array where Element:AssetProtocol {
    mutating func appendUpdateExclusive(element newAsset: Element) {
        newAsset.someInstanceMethod()
        Element.someStaticMethod()

        append(newAsset)
    }
}

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