Using diff in an array of objects that conform to

2019-07-12 20:21发布

问题:

I'm experimenting with using Composition instead of Inheritance and I wanted to use diff on an array of objects that comply with a given protocol.

To do so, I implemented a protocol and made it comply with Equatable:

// Playground - noun: a place where people can play
import XCPlayground
import Foundation

protocol Field:Equatable {
    var content: String { get }
}

func ==<T: Field>(lhs: T, rhs: T) -> Bool {
    return lhs.content == rhs.content
}

func ==<T: Field, U: Field>(lhs: T, rhs: U) -> Bool {
    return lhs.content == rhs.content
}

struct First:Field {
    let content:String
}

struct Second:Field {
    let content:String
}

let items:[Field] = [First(content: "abc"), Second(content: "cxz")] //               
                            
标签: swift lcs