mardi 31 janvier 2017

Protocol extension and generics in Swift 3. Is this even possible?

I'm reading Head First Design Patterns and I'm trying to replicate the Design Patterns in a Swift Playground. I'm trying to get the Observer pattern working as per the book. My current source is as follows:

protocol Subject {
    func register(observer: Observer)
    func remove(observer: Observer)
    func notifyObservers()
}

protocol Observer {
    func update(temperature: Double, humidity: Double, pressure: Double)
}

protocol DisplayElement {
    func display()
}

class WeatherData: Subject {

    var observers: [Observer]

    var temperature: Double!
    var humidity: Double!
    var pressure: Double!

    init() {
        observers = []
    }

    func register(observer: Observer) {
        observers.append(observer)
    }

    func remove(observer: Observer) {

    }

    func notifyObservers() {
        for obs: Observer in observers {
            obs.update(temperature: temperature, humidity: humidity, pressure: pressure)
        }
    }
}

What I need to do is to implement the removeObserver method. The snippet that I need to implement is something as:

func remove(observer: Observer) {
    let obs: Observer = observers.index(where: { (aObserver) -> Bool in
        return aObserver == observer
    })
}

However this is not allowing me to continue because of a compilation error:

Cannot convert value of type '(OptionalNilComparisonType) -> Bool' to expected argument type '() -> Bool'

Is it even possible to achieve this and what am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire