Reputation: 63
Using Swift 2.0 I have a problem conforming to a protocol. I broke down the code as much as possible to illustrate the issue.
protocol Filter {
var filterName:BaseModel {get}
}
protocol BaseModel {
var name: String {get}
}
enum SomeModel: BaseModel {
case Something
var name: String {
switch self {
case .Something:
return "yeah"
}
}
}
struct SomeFilter:Filter {
var filterName:SomeModel
}
With this code I get:
Type 'SomeFilter' does not conform to protocol 'Filter'
Since SomeModel is of type BaseModel (conforms to BaseModel) this should work. If I change change var filterName:SomeModel
to var filterName:BaseModel
in SomeFilter it works of course, but I can't figure out why it does not see SomeModel as a BaseModel.
Upvotes: 1
Views: 73
Reputation: 63
So basically I realised I didn't need to create custom filters, just custom Models and ended up with something like this.
protocol Model {
var name:String {get}
}
struct Filter {
var model:Model
}
enum SpecificModel: String, Model {
case Something, SomethingElse
var name: String {
switch self {
case .Something:
return "something"
default:
return rawValue
}
}
}
Upvotes: 0
Reputation: 5159
It's because var filterName: SomeModel
is not what the protocol is saying.
You might try something like this with generics to accomplish your idea.
protocol Filter {
typealias BaseModelType
var filterName: BaseModelType { get }
}
protocol BaseModel {
var name: String { get }
}
enum Model: BaseModel {
case A
case B
var name: String {
switch self {
case .A:
return "hello world"
case .B:
return "bye world"
}
}
}
struct SomeFilter<T: BaseModel>: Filter {
typealias BaseModelType = T
var filterName: BaseModelType
init(filterName: BaseModelType) {
self.filterName = filterName
}
}
let test = SomeFilter(filterName: Model.A)
test.filterName.name // prints "hello world"
I hope this might help you somehow. Any feedback is welcome.
Upvotes: 1